Sails js 客户端原生 websocket

Sails js client native websocket

我正在尝试将 websockets 与 sails-js 一起使用,但我无法使其与本机 javascript websockets 一起使用。

教程示例使用 sails.io.js 库,它有点像这样:

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);
    });

}

这确实有效,但我想像这样使用本机 javascript websockets:

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);

};

干净的原生 javascript websockets,不需要库。不幸的是,我似乎无法让它发挥作用。

当我尝试使用本机 websockets 连接到 sails js 服务器时,我收到此消息:

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

无法连接,似乎 sails js 甚至没有收到消息,因为我在获得新连接时创建了一个日志(使用教程代码):

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'
        });
    }
};

如何让 sails js 与原生 javascript websockets 一起工作?

找到一个简单的解决方案!

使用了 npm 包 ws:npm i ws

制作一个新的钩子:sails 生成钩子 customWebSocket

中钩:

/**
 * WS hook
 *
 * @description :: A hook definition.  Extends Sails by adding shadow routes, implicit actions, and/or initialization logic.
 * @docs        :: https://sailsjs.com/docs/concepts/extending-sails/hooks
 */
const WebSocket = require('ws');

module.exports = function defineWsHook(sails) {

  return {

    /**
     * Runs when this Sails app loads/lifts.
     */
    initialize: async function () {

      sails.log.info('Initializing custom hook (`WS`)');


      console.log("custom hook")

      const wss = new WebSocket.Server({ port: 3100 });


      wss.on('connection', (socket) => {
        console.log('New user connected wss');


        socket.on('message', function incoming(message) {


          console.log(message)


          
        });


      });
    }

  };

};

大功告成,现在我可以使用本机 websocket 连接了!

现在我已经完成了,我意识到 socket.io 库可能更适合处理错误。