javascript websocket 客户端中的 onmessage 事件没有被触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17607429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:57:14  来源:igfitidea点击:

onmessage event in websocket client is not getting fired

javascripthtmlnode.jswebsocket

提问by Sheetal Jadhwani

I am using node.js to implement websocket server and client. The handshake between them looks like this.

我正在使用 node.js 来实现 websocket 服务器和客户端。他们之间的握手是这样的。

Request URL: ws://localhost:8015/

请求地址:ws://localhost:8015/

Request Method: GET

请求方式:GET

Status Code: 101 Switching Protocols

状态代码:101 交换协议

Request Headers

请求头

Cache-Control: no-cache
Connection: Upgrade
Cookie: SQLiteManager_currentLangue=2
Host: localhost:8015
Origin: http:/localhost:8080
Pragma: no-cache
Sec-WebSocket-Extensions: x-webkit-deflate-frame
Sec-WebSocket-Key: A/knWtXFtTa5V6po8XOfjg==
Sec-WebSocket-Protocol: echo-protocol
Sec-WebSocket-Version: 13
Upgrade: websocket
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36

Response Headers

响应头

Connection: Upgrade
Origin: http:/localhost:8080
Sec-WebSocket-Accept: 5OUv+g5mBPxVDug4etJfGX4lxIo=
Sec-WebSocket-Protocol: echo-protocol
Upgrade: websocket

The server is getting the message sent from client (I am logging the message on console), however onmessage event in client is not getting fired when server sends the message. The other thing confusing me is as soon as connection is opened, onmessage event in clients gets fired only once.

服务器正在获取从客户端发送的消息(我正在控制台上记录消息),但是当服务器发送消息时,客户端中的 onmessage 事件没有被触发。另一件让我感到困惑的事情是,一旦打开连接,客户端中的 onmessage 事件只会触发一次。

Please help...I am trying to echo the message on the server back to client.

请帮忙...我正在尝试将服务器上的消息回显给客户端。

EDIT:

编辑:

This is how I am handling events in websocket client...

这就是我在 websocket 客户端中处理事件的方式...

html5WebSocketClient.connect = function(){
     if(window.WebSocket != undefined){
         if(connection.readyState == undefined || connection.readyState > 1)
             connection = new WebSocket('ws://localhost:8015/','echo-protocol');
     }
     if (window.MozWebSocket) {
          window.WebSocket = window.MozWebSocket;
     }

 connection.onopen = html5WebSocketClient.onOpen(event);
 connection.onmessage = html5WebSocketClient.onMessage(event);
 connection.onclose = html5WebSocketClient.onClose(event); 
 connection.onerror = html5WebSocketClient.onError(event);

};

};

html5WebSocketClient.onOpen = function(event)
{
    $('#some_label').text("Connected");
};

html5WebSocketClient.onClose = function(event)
{
    $('#some_label').text("Disconnected");
};

html5WebSocketClient.onError = function(event)
{
    $('#some_label').text("Error");
};

//This is only getting fired when connection opens
html5WebSocketClient.onMessage = function(message)
{
    if(message.data != undefined)
        {
        alert($.parseJSON(message.data));
    }
};

//Server is getting this message
html5WebSocketClient.sendMessage = function()
{
   var message = {"name": value, "name": value};
   connection.send(JSON.stringify(message));
};

And here's how I had implemented server..

这是我实现服务器的方式..

var http = require('http');
var WebSocketServer = require('websocket').server;

var server = http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Node.js From HTML5\n');
}).listen(8015, "127.0.0.1");

wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false
});

wsServer.on('request', function(request) {

    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.send(message.utf8Data); //Client is not getting this message..?
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

回答by freakish

These lines are responsible for your problem:

这些行负责您的问题:

connection.onopen = html5WebSocketClient.onOpen(event);
connection.onmessage = html5WebSocketClient.onMessage(event);
connection.onclose = html5WebSocketClient.onClose(event); 
connection.onerror = html5WebSocketClient.onError(event);

Let's analyze this. html5WebSocketClient.onOpen(event);calls onOpenwith argument event(which is undefined) and returns undefined(onOpendoes not return anything). Thus connection.onopenbecomes unedefined. But connection.onopenis supposed to be a function. So instead of calling these functions simply do this:

我们来分析一下。带有参数的html5WebSocketClient.onOpen(event);调用(即)并返回(不返回任何内容)。从而变成。但应该是一个函数。因此,不要调用这些函数,只需执行以下操作:onOpeneventundefinedundefinedonOpenconnection.onopenunedefinedconnection.onopen

connection.onopen = html5WebSocketClient.onOpen;
connection.onmessage = html5WebSocketClient.onMessage;
connection.onclose = html5WebSocketClient.onClose; 
connection.onerror = html5WebSocketClient.onError;