Began to study the WS protocol and it became not clear ...

 var clients = {}; var ws = new WebSocketServer.Server({ port: 3000 }); ws.on('connection', function(ws) { var id = random(1, 100) // min, - max clients[id] = ws; }); # ... 

as you see, when creating a connection, for each user, a connection object is added to the array ... it turns out that if I want to send a message to a specific user, I take this object and send ? But how then, if the user goes to another page of the site? (if it passes, the connection is broken and a new one is installed, with a new object ...) will this object be active so that I can notify it wherever it is?

I read somewhere that it’s enough to keep connections in the server’s memory, that is, in the clients variable. i.e:

 var clients = { questions: { 324: <ws_object> } } 

in questions there are questions identifiers (324 ... etc), those users who are subscribed to this question are added there ... again there is a problem with the new connection, you have to build crutches and add active connections ... and what if the server crashes? the whole structure will go to hell

It turns out, these objects of connection need to be stored in a БД ? if I want to notify the user, I take this object from the БД (by its id ) and send the data?

please explain how this all happens; identification mechanism and user management. thank!

  • What is the label ue ? - Qwertiy
  • typo corrected - cmd
  • youtube.com/… - Qwertiy

3 answers 3

WebSocket is an analogue of a regular socket, designed specifically for the case when a browser acts as a client. However, WebSockets can be used not only in conjunction with a browser. But it won't make much sense, it would be more correct to use regular sockets. In general, to use the WebSocket protocol, both the client and server are required to support this protocol. Modern browsers out of the box support WebSocket, so if a modern browser acts as a client, the floor has already been done. It remains to provide WebSocket support on the server side.

The interaction of two nodes (client and server) using sockets (WebSocket) is the creation of a permanent connection with two-way data transfer (two-way data transfer channel). To this end, a socket instance is created on each node. After that, each of the nodes can receive and transmit data over the established channel. It is important to understand that a channel has a pair of sockets - one on one node (client), the second on another node (server). In this context, the client initiates the connection, and nothing else. That is, the server expects new connections and processes them, but the initiator is always the client. After creating the channel, the data can be sent in any order, and then it all depends on the developer’s imagination.

The client-side instance of WebSocket has a lifetime of no more than the lifetime of the page, that is, with the closing of the page, the connection will be broken and the client instance of WebSocket is destroyed. This means that the corresponding server instance does not have more than a pair and it will no longer be possible to send / receive data on it. The server should monitor the disconnection and remove such sockets.

With the theory figured out, tips on the issue. In the database you need to store data that, if necessary, pass through sockets to the client. With the use of modern technologies like WebSocket protocol, it is worth moving to new standards for website development. It makes sense to look towards one-page sites. In this case, when you go to the site, a single page will be opened and, in general, a single instance of WebSocket will be created. Of course, the client also needs to consider handling exceptional situations. After all, the connection can be terminated without the initiative of the server. The client can re-create the connection if necessary.

Will this object be active so that I can notify it wherever it is?

I have already answered, paraphrasing. No, the server object will not be active and must be manually destroyed. The client must take care of himself, and create a new channel. It is important to provide an authentication mechanism - the server must somehow distinguish between clients. Although in general it is not necessary.

identification mechanism and user management

It doesn’t happen at all, more precisely it happens as the developer wishes. We need to understand a simple thing - WebSockets - this is just a mechanism for two-way data transfer over the network. You also need to understand that this very data transfer is based on a permanent connection. That is, two nodes are connected by a permanent connection and each of them can transmit anytime and any data. In the simplest case, you can restrict yourself to text data, but WebSockets also support binary data. Actually this is all you need to know to start. Further, regardless of the use of WebSockets, it is necessary to provide a data transfer protocol. The protocol can be built on messages.

An example of a client message for authorization:

 {type: "auth", login: "user", pass: "password"} 

Sample server response:

 {type: "auth", status: false} 

Ie the guest has connected to the server and is such until he sends the authorization message with the correct data, which the server will check and transfer the guest to an authorized user. For the above, it is still necessary to provide a registration procedure - specifically for creating new users.

This is a very broad topic, and you can write a book on it. I will sound some moments. The client (and server) in this context acts as a state machine, and only the developer can decide what logic will be implemented. Initially, the user enters the site unauthorized. It may be available part of the functionality, and maybe not. The server is obliged to keep the status of each client. A part of the state is like a connection (WebSocket), the authorization status can only be stored in the server’s memory, no more, besides WebSocket can’t be saved to the database, and it doesn’t make sense. And all other information about the status of users must be stored, for example, in the database. After server reboot (crash), this data will be available again.

Regarding the code: Your example is very simple and does not reflect the true state of affairs. To work with users, the server must distinguish them. Simple you need to create a class User with all the necessary data, and save it to the database. And under certain conditions (successful authorization) to associate the current connection with this user.

    To begin with, this is not PHP . That is, PHP is a scripting language, it will be executed and immediately terminated. And that's it! For each connection, a new process is created, the code is re-executed. NodeJS is a streaming server that runs continuously (!) In one process. Accordingly, the same memory space is available to it.

    As for your question: That is simple! If you want to store connection objects in the БД , then know that there will be problems with the serialization of this object .. This is a bad idea and you don’t need to do so. It is enough for objects to assign identification numbers to distinguish them:

    Registered users have their own id , so the value and the control mechanism is introduced.

    When opening a new connection, update the connection object with the user ID


    in questions there are question identifiers (324 ... etc), those users who are subscribed to this question are added there ...

     var clients = { questions: { 324: <ws_object> } } 

    It is not right. Logic itself must be stored in the БД (or in some storage). For if the script is completed, you will lose your saved question subscriptions.

    Create a separate table in the database, add there: who is subscribed to what. For example:

     qid | uid 324 | 54 

    User with ID 54 subscribed to question with ID 324

    When a new event appears, send alerts based on this table.

      here https://learn.javascript.ru/websockets pretty full description. you should add to @sba that websocket has a mechanism for tracking a break or disconnecting a connection. when you click on a new page, the ws connection will be new, but the user’s name will remain the same, so by that name, you must select the ws connection to send the message to the desired user.

      • > "but the name of the user will remain the same" it is not clear what name do you mean? - cmd
      • when the user logs in to the site using the password login - for the entire session the login / user name remains constant when navigating through the site pages. therefore, when moving to a new page, you need to bind the login to the ws connection. - Vadim
      • I wonder what kind of coward zaminusoval? or a fool? - Vadim