Multiple websocket connections

JavascriptClientWebsocket

Javascript Problem Overview


Is there any advantages of having two distinct websocket connections to the same server from the same client? To me this seems a bad design choice, but is there any reason why/where it should work out better?

Javascript Solutions


Solution 1 - Javascript

There are several reasons why you might want to do that but they probably aren't too common (at least not yet):

  • You have both encrypted and unencrypted data that you are sending/receiving (e.g. some of the data is bulky but not sensitive).
  • You have both streaming data and latency sensitive data: imagine an interactive game that occasionally has streamed video inside the game. You don't want large media streams to delay receipt of latency sensitive normal game messages.
  • You have both textual (e.g. JSON control messages) and binary data (typed arrays or blobs) and don't want to bother with adding your own protocol layer to distinguish since WebSockets already does this for you.
  • You have multiple WebSocket sub-protocols (the optional setting after the URI) that you support and the page wants to access more than one (each WebSocket connection is limited to a single sub-protocol).
  • You have several different WebSocket services sitting behind the same web server and port. The way the client chooses per connection might depend on URI path, URI scheme (ws or wss), sub-protocol, or perhaps even the first message from client to server.

I'm sure there are other reasons but that's all I can think of off the top of my head.

Solution 2 - Javascript

I found that it can make client logic much simpler when you are only subscribing to updates of certain objects being managed by the server. Instead of devising a custom subscription protocol for a single channel, you can just open a socket for each element.

Let's say you obtained a collection of elements via a REST API at

http://myserver/api/some-elements

You could subscribe to updates of a single element using a socket url like this:

ws://myserver/api/some-elements/42/updates

Of course one can argue that this doesn't scale for complex pages. However, for small and simple appications it might make your life a lot easier.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChristianView Question on Stackoverflow
Solution 1 - JavascriptkanakaView Answer on Stackoverflow
Solution 2 - Javascriptlex82View Answer on Stackoverflow