Javascript 在 socket.io 上关闭套接字服务器端?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7492966/
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
Closing a socket server side on socket.io?
提问by Derek
I'm pretty sure this is a simple question, but I have no idea where the socket.io docs are and the one at http://labs.learnboost.com/socket.io/don't really help.
我很确定这是一个简单的问题,但我不知道 socket.io 文档在哪里,而http://labs.learnboost.com/socket.io/ 上的文档并没有真正的帮助。
So let's say I have a socket.io http server and written a website to connect to it.
所以假设我有一个 socket.io http 服务器并编写了一个网站来连接它。
How do I provide protection to the server so that unauthorized people(people who connected not through the website) will be blocked/dropped/banned.
How do I end a socket connection on the server side? So If I have
io.sockets.on('connection', function (socket) { socket.on('end', function() { var i = global_sockets_list.indexOf(socket); global_sockets_list.splice(i, 1); }); socket.emit('end'); // Doesn't work, just sends data socket.end(); //error });
我如何为服务器提供保护,以便阻止/删除/禁止未经授权的人(未通过网站连接的人)。
如何结束服务器端的套接字连接?所以如果我有
io.sockets.on('connection', function (socket) { socket.on('end', function() { var i = global_sockets_list.indexOf(socket); global_sockets_list.splice(i, 1); }); socket.emit('end'); // Doesn't work, just sends data socket.end(); //error });
How do I end a socket connection? (The connect then disconnect above is for testing)
如何结束套接字连接?(上面连接然后断开是为了测试)
回答by Femi
Try calling:
尝试调用:
socket.disconnect('unauthorized');
or
或者
socket.close();
EDIT: You might be able to check the referer header. Look at Socket.io Security Issuesfor more info.
编辑:您也许可以检查引用标头。查看Socket.io 安全问题了解更多信息。
回答by Peter Lyons
On the server side there is a socket.disconnectmethod that takes a boolean meaning close the underlying transport connection. Here's the source code with docs as of July 2010:
在服务器端有一个socket.disconnect方法,它采用布尔值表示关闭底层传输连接。这是截至 2010 年 7 月的带有文档的源代码:
/**
* Disconnects this client.
*
* @param {Boolean} if `true`, closes the underlying connection
* @return {Socket} self
* @api public
*/
Socket.prototype.disconnect = function(close){
if (!this.connected) return this;
if (close) {
this.client.disconnect();
} else {
this.packet({ type: parser.DISCONNECT });
this.onclose('server namespace disconnect');
}
return this;
};
So you should call socket.disconnect(true);
所以你应该打电话 socket.disconnect(true);