Colin Rosati
Colin Rosati

Reputation: 332

Node.js HTTP server not able to respond to websocket

http server not responding to websocket

I am unable to have my http server respond to websocket requests. How do I correctly listen to these events? my server is running a SPA and I would like to try and use websockets to constantly send updated information from a file to the client. I have successfully done this with SSE but am curious about websockets.

My server.js has the following

const http = require('http');
const WebSocket = require('ws');

var server = http.createServer(function(request, response) {
   request.on('error', (err) => {
      console.error(err.stack);
   });
});

server.listen(8001);

const wss = new WebSocket.Server({ server });

wss.on('connection', function connection(ws) {
    ws.on('message', function message(msg) {
        console.log(msg);
      });
    });
});

my client.js

var wsClient = ()=>{
    const ws = new WebSocket('ws:'+serverip+'/WSindexJSON'); // this server is set through XHR request

    ws.onopen = function(e) {
       console.log("Connection established");
    };

    ws.addEventListener('open', () => {
      // Send a message to the WebSocket server
      ws.send('Hello!');
    });
    console.log("ws open",ws)

    ws.addEventListener('message', event => {
      // The `event` object is a typical DOM event object, and the message data sent
      // by the server is stored in the `data` property
      console.log('Received:', event.data);
    });
}

I am able to see the client websocket created in the chrome developer network tools, but nothing is coming through on the server. Do I need to create the websocket on the server side?

I have seen another example which the server listens for an upgrade event . I have tried that with no success.

server.on('upgrade', function upgrade(request, socket, head) {
      const pathname = url.parse(request.url).pathname;
      console.log('server upgrade event websocket', pathname)
      if (pathname === '/WSindexJSON') {
        wss.handleUpgrade(request, socket, head, function done(ws) {
          wss.emit('connection', ws, request);
        });
      } else {
        socket.destroy();
      }
    });

I have also tried another websocket module const WebSocketServer = require('websocket').server; and run into the same questions.

Upvotes: 0

Views: 1525

Answers (1)

Milan
Milan

Reputation: 2013

You need to specify port on which client will attempt to connect (in your case 8001):

var wsClient = ()=>{
    const ws = new WebSocket('ws:'+serverip+':8001/WSindexJSON');

Upvotes: 1

Related Questions