12

I have a site that has few thousands visits every month and its growing. I am adding new functionalities to my web that are interactive.

Now i am dealing with question, should i use one websocket connection for all functions or should i create new websocket connection for every interactive function of my app?

I am thinking about performance issues. Creating websocket means i have to save the connection on server. But multiple connection for one user = the amount of connection i have to save is much larger if i create new connection for every functionality.

What is the riht way how to deal with this?

jejjejd
  • 721
  • 1
  • 8
  • 18

1 Answers1

9

should i use one websocket connection for all functions or should i create new websocket connection for every interactive function of my app?

You should have only one websocket connection, there is no reason to use multiple websockets.

From my personal experience:

Best design would be to use a REST API to handle actions comming from client and use Websocket only for notifications. using REST would manage the parsing for you.

Anyway, if you want all your app to communicate through websocket protocol, you can send through the socket something like

msg = {
  "action": "fly",
   "data": "plane"
}

Then handle it in your server side using a switch case statement:

switch(msg.action){
case 'fly': 
serverCommand.fly(msg.data);
break;
// other statements
}

Or you can even do (no parsing needed):

serverCommand[msg.action](msg.data);

What I want to say is: you don't need to open multiple websockets to solve performance issues.

By opening multiple websocket for same client your code will be hardly maintainable and you will lost the DRY principle.

Take a look at that answer, which not recommend to open multiple sockets.

And this answer which enumarate all the case where you may want to open multiple websockets for same client (pay attention, that it says that uses case are not commons)

IsraGab
  • 4,819
  • 3
  • 27
  • 46
  • 1
    but wouldnt it become slow? If i send json, the server should parse the route first. For example i would have to send { route : 'chat' , data: "data"}. – jejjejd Aug 25 '18 at 21:37
  • Not it would not be slower than long pooling, nor slower than making new connections for each request. What is used mostly (performance and logic) is one connection, with some predefined packets (json/binary) that are routed in the app similar to current http requests. I dont know what you are using for http/websockets but for example i use very very similar routing inside, etc - just different transctiption for data that are sent to the client (binary on websocket, json on http) but json on websocket is also not as slow as you can think and is a good start to see how to do it at all – Seti Feb 15 '22 at 22:29