用于节点JS客户端的CLOSE_WAIT中的套接字

时间:2018-03-14 02:38:46

标签: python node.js sockets

我有一个python套接字服务器,我通过节点客户端连接到该服务器。问题是,即使在客户端退出(在销毁套接字之后),发生连接的TCP套接字仍处于CLOSE_WAIT状态。

Python服务器:

import socket
import sys

HOST = ''
PORT = 15000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(10)
print 'Socket now listening'

#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])
    conn.send("Hello, server here!")


s.close()

节点客户端:

var net = require('net');

var client = new net.Socket();

client.connect(15000, 'localhost', function() {
    console.log('Connected');
    client.write('Hello, server! Love, JS Client.');
    setTimeout(function() {
                client.destroy(); // kill client after server's response
        }, 3000);
});

client.on('close', function() {
    console.log('Connection closed', client.destroyed);
});

输出lsof -p the_server_pid:

python  31690 kai    3u  IPv4 1501142      0t0     TCP *:15000 (LISTEN)
python  31690 kai    4u  IPv4 1501143      0t0     TCP localhost:15000->localhost:34476 (CLOSE_WAIT)

另一方面,如果我使用节点服务器和上述相同的节点客户端,则不会发生问题。客户端退出后,套接字将关闭,并且我看不到处于CLOSE_WAIT状态的任何套接字。

节点服务器:

var net = require('net');

var tcpServer = net.createServer(function(socket){
    console.log('connection established....');

    socket.on('end', function(){
        console.log('server disconnected..');
        });

    socket.on('close', function(){
        console.log('closed event fired');
        });

    socket.on('data', function(data){
        socket.write('Hello, server here!' );
        });

    socket.on('error', function(error){
        console.log('something wrong happpened here');
        socket.destroy();
        });

    });

tcpServer.maxConnections=10;

tcpServer.listen(15000, function(){
    var port = tcpServer.address().port;
    console.log('server started listening on port: ' + port);
    });

总结我的问题:

python server + node client = CLOSE_WAIT; node server + node client = OK

想知道为什么会这样,也许我可能会在这里遗漏一些东西。非常感谢任何指导。

使用python 2.7.12,节点8.9.2和Ubuntu 16.04.03在本地计算机上测试

1 个答案:

答案 0 :(得分:0)

您应该使用client.end()代替client.destroy()。还有服务器上的socket.end()