【问题标题】:Sails js client native websocketSails js客户端原生websocket
【发布时间】:2021-04-24 02:05:44
【问题描述】:

我正在尝试将 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 websocket:

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 服务器时,我收到以下消息:

到 'ws://localhost:1337/websockets/hello' 的 WebSocket 连接失败:在收到握手响应之前连接已关闭

无法连接,似乎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 一起工作?

【问题讨论】:

    标签: javascript websocket sails.js


    【解决方案1】:

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

    使用了 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 库可能更适合处理错误。

    【讨论】:

    • 如果我们采用这种方法,我们如何从服务或控制器访问套接字实例?如何让socket实例像sails js内置的socket机制一样全局可用?
    猜你喜欢
    • 1970-01-01
    • 2018-04-11
    • 2016-11-02
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 2018-08-23
    相关资源
    最近更新 更多