【发布时间】:2015-11-29 14:31:43
【问题描述】:
我正在尝试制作一个简单的 Node.js 脚本,如果未使用分配的端口,它会创建一个服务器,如果正在使用该端口,它会连接到服务器。我对此使用递归方法(使用this 链接作为参考),所以我在两个不同的cmd 窗口上运行相同的.js 文件。
问题是每当客户端连接到服务器时,它会自动进入“结束”侦听器,我不知道为什么。在阅读文档后,我发现了allowHalfOpen属性,其中API中有以下说法:
如果allowHalfOpen为真,那么当socket的另一端发送FIN包时,socket不会自动发送FIN包。
我认为这是显而易见的解决方案,所以我在服务器上将属性设置为 true,但这也没有用。
代码如下:
var net = require('net');
var PORT_NUMBER = 1337;
connectToPort = function(connection) {
if(connection === "server") { // Connect as server to the port.
connectAsServer();
} else if (connection == "client") { // Connect as client to the port.
connectAsClient();
} else {
console.log("Incorrect Type Of Connection Passed.");
}
}
connectAsServer = function() {
// Attempt to create server.
var server = net.createServer({allowHalfOpen:true}, function (socket) {
socket.allowHalfOpen = true;
socket.write('Hello from Server\r\n');
socket.end("hello");
console.log("someone went into server.");
socket.pipe(socket);
});
console.log("Trying to Open Port " + PORT_NUMBER);
server.listen(PORT_NUMBER, function() {
console.log("\nServer 2 is now the official server. \n");
});
server.on('error', function(err) {
console.log("error is " + err.code);
if(err.code == 'EADDRINUSE') {
console.log('Port is in use, becoming client...');
setTimeout(function () {
server.close();
connectToPort("client");
}, 1000);
}
if(err.code == 'ECONNRESET') {
console.log("connection reset error.");
}
});
server.on('end', function() {
console.log("server 2 disconnected from port");
});
}
connectAsClient = function() {
var client = net.connect({port: PORT_NUMBER}, function() { //'connect' listener
console.log('THIS IS CLIENT connected to server!');
});
client.on('data', function(data) {
console.log(data.toString());
client.write('hello world! from client!!\r\n');
});
client.on('end', function() {
// client automatically goes here.
console.log('disconnected from server');
});
client.on('error', function(err) {
console.log("there was an error in the client and the error is: " + err.code);
});
}
connectToPort("server");
以下是控制台的输出:
对于服务器:
对于客户:
我想要的本质上是让客户端仅在服务器关闭或发生其他事件时断开连接。但理想情况下,我希望它连接到服务器以在它们之间交换数据。
我做错了什么吗?为什么服务器端的allowHalfOpen为真,还是发送FIN包?
谢谢,
【问题讨论】:
标签: javascript node.js sockets server client