Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS socket on a port *and* a path?

I want to set up a basic socket on a URI like ws://localhost:1234/mysocket (to mimic another environment created with Java), Thus far I've only been able to set it up on ws://localhost:1234/ How can I get it to host on a specific URL beyond just a host and port?

This is just the basic NodeJS socket from the docs:

var net = require('net');

var server = net.createServer(function (socket) {
  socket.write('Echo server\r\n');
  socket.pipe(socket);
});

server.listen(1337, '127.0.0.1'); // <-- not sure what to do here?

I'm specifically not asking for a solution involving Socket.IO.

Edit

I feel like maybe I actually need to set up a proxy in front of my socket server? But that seems a little bizarre.

like image 880
Ben Lesh Avatar asked Oct 14 '14 17:10

Ben Lesh


1 Answers

Since you're already using WebSockets, you can simply use the ws module:

var http = require('http'),
    WebSocketServer = require('ws').Server;

var server = http.createServer();

var wss = new WebSocketServer({
    server: server,
    path: '/mysocket'
});

wss.on('connection', function (ws) {

    ws.send('echo server');

    ws.on('message', function (message) {
        ws.send(message);
    });

});

server.listen(1234);
like image 101
ldmat Avatar answered Oct 05 '22 21:10

ldmat