如何在websocket服务器中保持连接的值?

时间:2014-04-24 06:09:36

标签: node.js websocket

下面是使用" ws"的websocket服务器端代码。插件。

var WebSocketServer = require('ws').Server
   ,wsSend = new WebSocketServer({port: 8080}) //Client sends message on this port.
   ,wsReceive = new WebSocketServer({port: 8081}) //Response is sent on this port.
   ,clientMessage;

    wsSend.on('connection', ReceiveSocketConnection);//From client.

    //Callback function on connection with client.
    function ReceiveSocketConnection(webSocket) {
        webSocket.on('message', GetMessageFromClient);
    }

    //Handler to receive message from client.
    function GetMessageFromClient(messageFromClient) {
       clientMessage = messageFromClient; //Message from client saved into variable
    }

    wsReceive.on('connection', SendSocketConnection);//To client.

    function SendSocketConnection(webSocket) {
        webSocket.send(clientMessage);//Here clientMessage is undefined
    }

以下是客户端代码。

var WebSocket = require('ws')
        , wsSend = new WebSocket('ws://localhost:8080') //send port
        , wsReceive = new WebSocket('ws://localhost:8081'); //receive port


        //Open connection on send port.  
        wsSend.on('open', function() {
            wsSend.send('Hi I am new to websockets');
        });

        //Open connection on receive port.  
        wsReceive.on('open', function() {
            //Do nothing
        });

        //Receive message from server via port 8081
        wsReceive.on('message', function(message) {
            console.log('received: %s', message);
        }); 

用于发送和接收消息的单独端口是存在的,因为它是一个设计决策。

我希望通过在一个端口上接收并将其发送到另一个端口来回显该消息。

问题:来自客户端的消息未保存到本地变量(即clientMessage)。有任何建议吗?

1 个答案:

答案 0 :(得分:0)

这应该有用,但我建议使用http://socket.io/

var WebSocketServer = require('ws').Server
   ,wsSend = new WebSocketServer({port: 8080}) //Client sends message on this port.
   ,wsReceive = new WebSocketServer({port: 8081}) //Response is sent on this port.

wsReceive.broadcast = function(data) {
  for(var i in this.clients)
  this.clients[i].send(data);
};

wsSend.on('connection', function(ws) {
  ws.on('message', function(message) {
    console.log('received: %s', message); 
    try {
      console.log('sending: %s', message);
      wsReceive.broadcast(message);
    } catch (e) {
       console.log(e);
    }
  });
});