3

I'm writing a websocket server using nodejs-ws module, but the server can only be at the root of the server, so how I can make it at a child router like localhost:3000/chat?

I need your help, thanks a lot!

2 Answers 2

4

Working example:

var ws = require('ws');
var http = require('http');

var httpServer = http.createServer();
httpServer.listen(3000, 'localhost');

var ws1 = new ws.Server({server:httpServer, path:"/chat"});
ws1.on('connection', function(){
  console.log("connection on /chat");
});

var ws2 = new ws.Server({server:httpServer, path:"/notifications"});
ws2.on('connection', function(){
  console.log("connection on /notifications");
});
Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot, and could you please tell me how to use this in express?
0

could you please tell me how to use this in express?

To route websockets with Express I'd rather use express-ws-routes

var express = require('express');
var app = require('express-ws-routes')();

app.websocket('/myurl', function(info, cb, next) {
    console.log(
        'ws req from %s using origin %s',
        info.req.originalUrl || info.req.url,
        info.origin
    );

    cb(function(socket) {
        socket.send('connected!');
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.