14

I have a simple webserver like

var http = require('http'),
    url = require('url');
var server = http.createServer(function (req, res) {
  var uri = url.parse(req.url).pathname;
  if (uri == '/') {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
    return;
  }

  res.writeHead(404, {'Content-Type': 'text/plain'});
  res.end('File not found');
});
server.listen(0, '127.0.0.1');

I would now like to connect a single path (say, /ws) to a websocket, but leave the rest of the server unmodified.

However, ws seems to require me to set up a dedicated server (with everything that that entails, like SSL termination, security configuration, and port allocation).

How can I terminate just the path /ws to a websocket implementation?

1
  • Maybe using a reverse proxy to handle incomming connections could help.
    – Philipp
    Commented Jan 11, 2013 at 8:27

2 Answers 2

15

I would recommend using the websocket package, it is a

Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.

Which is what I wanted so it's why I use it. It's incredibly painless to use and I'm actually doing both wss and ws connections to node.js from html clients using pure javascript websockets.

The git project is active, when I've posted issues I've had a response on the same day. An example from the link above shows how simple it is:

var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8080, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }

    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

I should note, however, that the subprotocols is not obvious, as there is no example. There are some questions on the git site for the project that lead you in the right direction though.

3
  • Yes, that seems like the best choice, although as mentioned, the example code sucks. I asked the question in the github issue tracker ;)
    – phihag
    Commented Jan 11, 2013 at 14:34
  • If you like you can look at my project on github, it's relatively clean and shows an example of using both ws and wss at the same time. I also perform protocol checking and do my own authentication via bcrypt. Note I'm currently changing it to support configurable types of connectivity (secure only, unsecure only, mixed mode), should be done in the next 8 hours.
    – Metalskin
    Commented Jan 11, 2013 at 23:18
  • I've created a new project when provides a complete websocket implementation between a node.js backend and html front end. It's designed to be used as a template to create your own solution. github.com/jamesjenner/meltingpot It includes a complete working example that is very easy to extend.
    – Metalskin
    Commented Nov 19, 2014 at 23:24
2

You may add the socket.io on the same port with your app. If you want the /ws path, then use:

var io = require('socket.io').listen(httpServer, { resource: '/ws/socket.io' });

Or have /ws point to /ws/socket.io

2
  • 3
    That looks good, but I'm amazed to find out that socket.io does not actually support plain WebSockets, but only their own protocol on top of it.
    – phihag
    Commented Jan 11, 2013 at 8:59
  • 2
    that's a common misundestanding - people (including the author) conflate socket.io with WebSockets, when in practise socket.io just presents a WebSocket-like interface that might be using WebSockets as its underlying transport. Or might not.
    – Alnitak
    Commented Dec 17, 2015 at 15:01

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.