Avi*_*ohn 9 javascript tcp http node.js server
我无法在Google或SO上找到明确的答案.
我知道一个net.Server实例有一个close方法,不允许更多的客户端.但它不会断开已经连接的客户端.我怎样才能做到这一点?
我知道如何用Http做到这一点,我想我问的是它与Tcp是否相同或是否有所不同.
有了Http,我会做这样的事情:
var http = require("http");
var clients = [];
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("You sent a request.");
});
server.on("connection", function(socket) {
socket.write("You connected.");
clients.push(socket);
});
// .. later when I want to close
server.close();
clients.forEach(function(client) {
client.destroy();
});
Run Code Online (Sandbox Code Playgroud)
对于Tcp来说是一样的吗?或者我应该采取不同的方式吗?
由于未提供答案,以下是如何在node.js中打开和(硬)关闭服务器的示例:
创建服务器:
var net = require('net');
var clients = [];
var server = net.createServer();
server.on('connection', function (socket) {
clients.push(socket);
console.log('client connect, count: ', clients.length);
socket.on('close', function () {
clients.splice(clients.indexOf(socket), 1);
});
});
server.listen(8194);
Run Code Online (Sandbox Code Playgroud)
关闭服务器:
// destroy all clients (this will emit the 'close' event above)
for (var i in clients) {
clients[i].destroy();
}
server.close(function () {
console.log('server closed.');
server.unref();
});
Run Code Online (Sandbox Code Playgroud)
更新:自从使用上面的代码后,我遇到了一个问题,即close打开端口(Windows中的TIME_WAIT).由于我故意关闭连接,我使用的是unref,因为它似乎完全关闭了tcp服务器,但如果这是关闭连接的正确方法,我不是100%.
| 归档时间: |
|
| 查看次数: |
7041 次 |
| 最近记录: |