Search code examples
websocketjava-websocket

How many WebSocket connection can be created on Client Side


I have started to learn web sockets. It is must learn technology in today's time. But i am curious to learn more about it. My basic question is How many WebSocket connection can be created on Client Side.

My Typically Application is html UI based and on the server i have rest based services. I need to track whether

  1. Session timeout has happed or not
  2. Whether Connection to the server is lost or not ? A kind of pooling program to check with connections is alive or not.

So I am creating 2 websocket objects on client and different url for them.

I hope i have implemented it correctly ?


Solution

  • Basically Browser closes the old websocket connection once you opened to new connection to SAME URL(ws://127.0.0.1:8080/WebSocket-context-root/getResource). You can keep small hack like "ws://127.0.0.1:8080/WebSocket-context-root/getResource/"+k. where k is any number/any random string. On server side just ignore the path variable k.

    In this way you can open many number of connection at same time. Browser restriction of max-number-connection per domain is not applying here (Tested on Firefox). I tried max 25 parallel connections.

    You can use websocket.readyState to check the status of the web socket connection.

    onclose Event of the Web socket have reason code for closed connection.

    User below code to test number of active connections.

         var x=0
         var intervalID = setInterval(function () {
         websocket = new WebSocket("ws://127.0.0.1:8080/WebSocketApi/web/chat/"+x);
    
          websocket.onopen = function (evt) {
    
          console.log('open')
          }
    
          websocket.onmessage = function (evt) {
                console.log('msg');
            }
          websocket.onclose= function (evt) {
                console.log('closed');
            }
          if (++x === 15) {
              window.clearInterval(intervalID);
          }
    
     }, 1);