【问题标题】:npm 'websocket' server send message to clientnpm 'websocket' 服务器向客户端发送消息
【发布时间】:2018-10-25 12:38:49
【问题描述】:

在我继承的代码中使用了this websocket。我阅读了文档并进行了大量谷歌搜索,以找到 websocketServer 如何向客户端(浏览器)发出消息。这是一个代码sn-p:

    var wsServer = new WebSocketServer({
        httpServer: server,
        autoAcceptConnections: false,
        path:"/async" //This attribute is not in the documentation
    });

  wsServer.on('request', function(request) {
    var connection = request.accept('relay_protocol', request.origin);
    connection.on('message', function(message) {
       ....
       });
     });

我找不到connection 对象的文档。它有什么特性?

最后,使用什么方法将消息发送回客户端?

总的来说,为这个模块提供的信息很差。请帮忙。

【问题讨论】:

    标签: javascript node.js websocket


    【解决方案1】:

    此模块的完整文档是here

    来自他们的示例(服务器):

    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.sendUTF(message.utf8Data);
    
    connection.sendBytes(message.binaryData);
    

    我希望这会有所帮助!

    提示:试用socket.io 模块。

    【讨论】:

    • 当我使用 socket.io 并将 websocket 使用的同一台服务器传递给它的配置时,它会阻止 websocket 本身。我不知道为什么。
    • Socket.IO 尽可能使用长轮询和 websocket。要仅使用 websocket,请添加以下配置:传输:['websocket']。更多:socket.io/docs/server-api
    猜你喜欢
    • 2022-07-15
    • 2017-09-15
    • 1970-01-01
    • 2015-01-05
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多