Sails js client native websocket

I’m trying to use websockets with sails-js but I can’t make it work with native javascript websockets.

the tutorial example use the sails.io.js library and it goes a little bit like this:

io.socket.on('hello', function (data) {
    console.log('Socket `' + data.id + '` joined the party!');
});

function sendHello () {

    // And use `io.socket.get()` to send a request to the server:
    io.socket.get('/websockets/hello', function gotResponse(data, jwRes) {
        console.log('Server responded with status code ' + jwRes.statusCode + ' and data: ', data);
    });

}

This does work, but i want to use the native javascript websockets like this:

let ws = new WebSocket("ws://localhost:1337/websockets/hello");


ws.onopen = function (e) {
    console.log("[open] Connection established");
    console.log("Sending to server");
    ws.send("My name is John");
};

ws.onmessage = function (event) {
    console.log(`[message] Data received from server: ${event.data}`);
};

ws.onclose = function (event) {
    if (event.wasClean) {
        console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
    } else {
        // e.g. server process killed or network down
        // event.code is usually 1006 in this case
        console.log('[close] Connection died');
    }
};

ws.onerror = function (error) {
    console.log(`[error] ${error}`);
    console.log(error);

};

Clean and native javascript websockets with no library needed. Unfortunately I can’t seem to make it work.

When I try to connect to sails js server using native websockets I get this message:

WebSocket connection to ‘ws://localhost:1337/websockets/hello’ failed: Connection closed before receiving a handshake response

Impossible to make it connect, it seems like sails js don’t even get the message because i make a log when i get a new connection (using the tutorial code):

module.exports = {
    hello: function (req, res) {

        console.log("web socket received",req.isSocket)

        // Make sure this is a socket request (not traditional HTTP)
        if (!req.isSocket) {
            return res.badRequest();
        }

        // Have the socket which made the request join the "funSockets" room.
        sails.sockets.join(req, 'funSockets');

        // Broadcast a notification to all the sockets who have joined
        // the "funSockets" room, excluding our newly added socket:
        sails.sockets.broadcast('funSockets', 'hello', { howdy: 'hi there!' }, req);

        // ^^^
        // At this point, we've blasted out a socket message to all sockets who have
        // joined the "funSockets" room.  But that doesn't necessarily mean they
        // are _listening_.  In other words, to actually handle the socket message,
        // connected sockets need to be listening for this particular event (in this
        // case, we broadcasted our message with an event name of "hello").  The
        // client-side code you'd need to write looks like this:
        // 
        //   io.socket.on('hello', function (broadcastedData){
        //       console.log(data.howdy);
        //       // => 'hi there!'
        //   }
        // 

        // Now that we've broadcasted our socket message, we still have to continue on
        // with any other logic we need to take care of in our action, and then send a
        // response.  In this case, we're just about wrapped up, so we'll continue on

        // Respond to the request with a 200 OK.
        // The data returned here is what we received back on the client as `data` in:
        // `io.socket.get('/say/hello', function gotResponse(data, jwRes) { /* ... */ });`
        return res.json({
            anyData: 'we want to send back'
        });
    }
};

How can I make sails js work with native javascript websockets?

64 thoughts on “Sails js client native websocket”

Leave a Comment