Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if WebSocket Server is running (on localhost)

When I try to initialize a websocket connection to the server running on localhost with

var webSocket = new WebSocket("ws://localhost:8025/myContextRoot");

in javascript, but the server hasn't completed starting up yet, I get the error

SCRIPT12029: WebSocket Error: Network Error 12029, A connection with the server could not be established

How can I prevent this? I.e. how do I check if the server has already started or how can I force the WebSocket client to wait for the server?

like image 565
Jakob Avatar asked Feb 08 '17 12:02

Jakob


People also ask

How do I know if WebSocket is running?

You can check if a WebSocket is connected by doing either of the following: Specifying a function to the WebSocket. onopen event handler property, or; Using addEventListener to listen to the open event.

Does WebSocket work on localhost?

Websockets work on localhost but not on public domain with apache.


2 Answers

What about:

var webSocketFactory = {
  connectionTries: 3,
  connect: function(url) {
    var ws = new WebSocket(url);
    ws.addEventListener("error", e => {
      // readyState === 3 is CLOSED
      if (e.target.readyState === 3) {
        this.connectionTries--;

        if (this.connectionTries > 0) {
          setTimeout(() => this.connect(url), 5000);
        } else {
          throw new Error("Maximum number of connection trials has been reached");
        }

      }
    });
  }
};

var webSocket = webSocketFactory.connect("ws://localhost:8025/myContextRoot");

When you get a connection error, you can do a limited number of trial-errors to try to re-connect. Or you can endlessly try to reach the server.

like image 108
Matías Fidemraizer Avatar answered Oct 02 '22 10:10

Matías Fidemraizer


The accepted answer is perfectly fine. I just would like to extend it a little bit further with promises.

var wsFactory = { tryCount: 3,
                  connect : function(url){
                              var ctx = this,
                                  ws  = new WebSocket(url);

                              return new Promise(function(v,x){
                                                   ws.onerror   = e => { console.log(`WS connection attempt ${4-ctx.tryCount} -> Unsuccessful`);
                                                                         e.target.readyState === 3 && --ctx.tryCount;
                                                                         if (ctx.tryCount > 0) setTimeout(() => v(ctx.connect(url)), 1000);
                                                                         else x(new Error("3 unsuccessfull connection attempts"));
                                                                       };
                                                   ws.onopen    = e => { console.log(`WS connection Status: ${e.target.readyState}`);
                                                                         v(ws);
                                                                       };
                                                   ws.onmessage = m => console.log(m.data);
                                                 });
                            }
                };

wsFactory.connect("ws://localhost:8025/myContextRoot")
         .then(ws => ws.send("Hey..! This is my first socket message"))
         .catch(console.log);
like image 25
Redu Avatar answered Oct 02 '22 10:10

Redu