1

I have a websocket with URL "ws://localhost:1122" running in my machine. I am able to connect to the websocket when using it with normal javascript and deploying it in a jetty server.

But while using node js I could not connect to the web socket. I use the following code in both cases

var socket = new WebSocket(URL);

While using node js I have addded the following var WebSocket = require("ws"). But the readyState of the socket never become OPEN in node js.

Is there anything I am missing in node js because while using jetty as a server and normal javascript I am able to connect to the websocket.

Here is my app.js

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(1131, "localhost");
var WebSocket = require("ws");
var wsUri = "ws://localhost:1122";
var socket;
printer();
function printer() {    
 socket = new WebSocket(wsUri);    
 console.log(socket.readyState);    
}
3
  • Can you post the whole server code ? You may have an error when or before you try to make the server listen. Commented Nov 14, 2018 at 13:20
  • Updated the question with app.js. Commented Nov 14, 2018 at 13:48
  • The server is listening to the port 1131. You cannot connect with the port 1122 on the client. Commented Nov 14, 2018 at 14:08

1 Answer 1

1

Because of the asynchronous nature of Node.js, socket.readyState doesn't immediately reflect the state of the connection.

Instead, you should use the event emitter interface to check if/when the connection is being made:

socket = new WebSocket(wsUri);
socket.on('open', function() {
  console.log('connection opened');
}).on('close', function() {
  console.log('connection closed');
}).on('error', function(e) {
  console.log('connection error', e);
});
Sign up to request clarification or add additional context in comments.

2 Comments

robertklep - I used this, the socket.on('open') functions gets skipped due to the asynchronous nature of node js. But executes once the connection is made. Is there a way to make this synchronous?
"executes once the connection is made". That's how event emitters work: they call the function when a particular event occurs :D You can't make it synchronous.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.