我正在用socketio
编写一个简单的WebSocket
应用程序。有2套接字事件,我可以实现,在连接和消息。第一个使用套接字作为参数(客户端),第二个使用从客户端发送的数据。所以我可以这样写,在消息事件中使用套接字变量:
WebSocketNoaListener.onClientConnect = function(socket){
var soc = socket;
socket.on("message", function(msg){
console.log("i can use message: "+msg);
console.log("and the socket: "+soc.id);
});
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect);
}
但我想分开我的函数更好的可读性:
WebSocketNoaListener.onClientConnect = function(socket){
var soc = socket;
socket.on("message", WebSocketNoaListener.onClientMessage);
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect);
}
WebSocketNoaListener.onClientMessage = function(){...
我需要在接收socket
的函数之外的作用域中使用soc
变量。这可能吗?
你真的应该这样做,而不是污染全局空间(此外,在另外两个答案中给出的解决方案不能处理两个同时连接,因为soc
在每个连接上都被覆盖)。
WebSocketNoaListener.onClientMessage = function(soc, msg){
console.log("i can use message: " + msg);
console.log("and the socket: " + soc.id);
};
WebSocketNoaListener.onClientDisconnect = function(soc, event){
console.log("not implemented in question");
};
WebSocketNoaListener.onClientConnect = function(socket){
socket.on("message", WebSocketNoaListener.onClientMessage.bind(this, socket));
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect.bind(this, socket));
}
在onClientConnection函数之外初始化soc
。
var soc;
WebSocketNoaListener.onClientConnect = function(socket){
soc = socket;
socket.on("message", WebSocketNoaListener.onClientMessage);
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect);
}
soc
现在可以在onClientConnect之外访问
ok这里是websocket特定的最终答案;
WebSocketNoaListener.onClientConnect = function(socket){
var soc = socket;
socket.on("message", WebSocketNoaListener.onClientMessage);
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect);
}
WebSocketNoaListener.onClientMessage = function(msg){
console.log("this is the message "+msg);
console.log("and this is the id of the socket "+this.id);
//'this' points here the socket itself
}