写了一个小例子。TCP服务器是在vc里实现的,循环等待客户端的数据连接,接收到客户端传来的特定值(STOP_CTRL: 4848)时断开连接。客户端里TCP连接的启停由我手动控制。
function ctrl_start() {
socket.connect(TCP_PORT, TCP_HOST, function() {
console.log("connected to: " + TCP_HOST + ":" + TCP_PORT);
});
}
function ctrl_stop() {
buf.writeUInt32LE(STOP_CTRL, 0);
socket.end(buf);
socket.destroy();
console.log("destroy "+STOP_CTRL);
}
经测试,连接的启停都进行的很好。可是命令行中打印结果如下:
connected to: 192.168.1.126:6969
destroy 4848
TCP Connection closed
connected to: 192.168.1.126:6969
connected to: 192.168.1.126:6969
destroy 4848
TCP Connection closed
即每次启动时,都会增加一条socket连接信息。可是我在停止连接的时候调用了socket.destroy()的啊?这是为什么?
4 回复
一次socket连接ctrl_start却被调用了2次,或者
console.log("connected to: " + TCP_HOST + ":" + TCP_PORT);
此语句也出现代码的其他地方并同样被执行了。 嘛,ctrl_start函数多加个console.log,把输出信息贴出来吧
function ctrl_start() {
socket.connect(TCP_PORT, TCP_HOST, function() {
console.log("connected to: " + TCP_HOST + ":" + TCP_PORT);
});
console.log(new Error().stack);
}
添加了你写的Error().stack,输出的信息如下
Error
at ctrl_start (D:\tools\nodejs\RC\RCserver.js:104:14)
at Socket.<anonymous> (D:\tools\nodejs\RC\RCserver.js:60:4)
at Socket.$emit (events.js:67:17)
at SocketNamespace.handlePacket (D:\tools\nodejs\node_modules\socket.io\lib\
namespace.js:335:22)
at Manager.onClientMessage (D:\tools\nodejs\node_modules\socket.io\lib\manag
er.js:469:38)
at WebSocket.onMessage (D:\tools\nodejs\node_modules\socket.io\lib\transport
.js:387:20)
at Parser.<anonymous> (D:\tools\nodejs\node_modules\socket.io\lib\transports
\websocket\hybi-16.js:39:10)
at Parser.emit (events.js:67:17)
at D:\tools\nodejs\node_modules\socket.io\lib\transports\websocket\hybi-16.j
s:288:16
at Parser.expectHandler (D:\tools\nodejs\node_modules\socket.io\lib\transpor
ts\websocket\hybi-16.js:299:15)