admin管理员组

文章数量:1291102

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

Request URL: ws://localhost:8015/

Request Method: GET

Status Code: 101 Switching Protocols

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.

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...

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

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

Request URL: ws://localhost:8015/

Request Method: GET

Status Code: 101 Switching Protocols

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.

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...

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.');
    });
});
Share Improve this question edited Jul 12, 2013 at 15:31 Sheetal Jadhwani asked Jul 12, 2013 at 4:26 Sheetal JadhwaniSheetal Jadhwani 851 gold badge3 silver badges9 bronze badges 2
  • Show us some code. I doubt this is related to the handshake. – freakish Commented Jul 12, 2013 at 9:04
  • @freakish:I have added websocket client and server code above..please help.. – Sheetal Jadhwani Commented Jul 12, 2013 at 15:33
Add a ment  | 

1 Answer 1

Reset to default 7

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 onOpen with argument event (which is undefined) and returns undefined (onOpen does not return anything). Thus connection.onopen bees unedefined. But connection.onopen is supposed to be a function. So instead of calling these functions simply do this:

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

本文标签: javascriptonmessage event in websocket client is not getting firedStack Overflow