venkat
venkat

Reputation: 487

Unable to connect to a websocket in node js

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);    
}

Upvotes: 1

Views: 3152

Answers (1)

robertklep
robertklep

Reputation: 203514

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);
});

Upvotes: 1

Related Questions