Search code examples
ember.jswebsocketember-clihttp-mock

How to stop Ember CLI's http-mock server throwing an error when there are websockets in one of the server files?


I have a websocket in one of my http-mock server files initialised as follows:

var WebSocketServer = require('ws').Server;
var socketServer = new WebSocketServer({port: 13434, path: "/update"});

and later in the file I have the following happen on connection:

socketServer.on('connection', function(ws) {
    ws.on('close', function(message) {
        clearInterval(sendResults);
    });

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

    sendResults = setInterval(function() {
        ws.send(JSON.stringify(getResultsFromEntries()));
    }, resultInterval);
});

However, whenever I edit any of the server files I get the following error:

File changed: "mocks/entry.js"

Just getting started with Ember? Please visit http://localhost:4200/ember-getting-started to get going

events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE 0.0.0.0:13434
    at Object.exports._errnoException (util.js:907:11)
    at exports._exceptionWithHostPort (util.js:930:20)
    at Server._listen2 (net.js:1250:14)
    at listen (net.js:1286:10)
    at net.js:1395:9
    at nextTickCallbackWith3Args (node.js:453:9)
    at process._tickCallback (node.js:359:17)

I'm guessing I need to detect when the file change happens and close the current websocket connection. On process exit doesn't seem to get called until the server dies, and then process.on('exit', function() {}) is called the number of times the server has refreshed. It doesn't bother me too much as I have a script that restarts ember server if it goes down, but other developers don't like the ember server going down when they edit a server file. Any ideas?


Solution

  • I ended up setting a new WebSocketServer as a property of process (which persists over the server getting restarted) then at the top of the file I close the previous WebSocketServer (if there was one):

    if (process["updateSocketServer"]) {
        process["updateSocketServer"].close();
        process["updateSocketServer"] = undefined;
    }
    

    Then setup a new WebSocketServer:

    process["updateSocketServer"] = new WebSocketServer({port: 13434, path: "/update"});
    

    Then I did the following on connection:

    process["updateSocketServer"].on('connection', function(ws) {
        // Connection code.
    });