简体   繁体   中英

Integer variable common for all sessions in node.js

How to have an integer variable common for all client sessions in node.js and access them in client html? (that is, I need a integer variable which can be displayed in the html page and can be updated in html page. The new updated value should be displayed for other clients.) I knew this is a silly question. But I am sorry. I am totally new to node.js and I do not have much time. I need a solution at the earliest. Thank you.

There are multiple options for getting the common variable into a web page:

  1. You can embed an actual <script> tag with the variable in every page that is served from the server. This technique would be easiest if using a template engine so that a common sub-template can be included in every page.

  2. You can have each page send an ajax call to the server when it first loads to fetch the value of the variable.

  3. You can have each page create a webSocket connection to the server when it first loads and then when the server receives the connection, it can send back the value of the variable.

When the client wants to update the variable, it has a couple options for informing the server:

  1. If using the webSocket connection above, it can just send a message to the server that the variable has been uddated and send the new value. The server can then broadcast to the other webSocket-connected clients what the new value is.

  2. If using the either of the other two options above, then whenever the client wants to change the value, it can issue an ajax call to the server to update the value. Other than the webSocket option above, the only way for the other clients to know when the value of the variable changes is for each client to regularly poll the server asking to fetch the current value of the variable (say every 30 seconds or so). This is not particularly efficient.

Because part of your problem is for all connected clients to know when the variable has change, you need the ability for the server to "push" an updated value to all clients. This is what webSockets were invented for and would likely be the recommended option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM