下面是使用"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)中。有什么建议吗?
这应该有效,但我建议使用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);
}
});
});