Socket in CLOSE_WAIT for node JS client

fox_hound_33 Source

I have a python socket server to which i am connecting via a node client. The issue is that the TCP socket via which the connection occurs is left in CLOSE_WAIT state even after the client has exited (after destroying the socket).

Python Server:

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
    s.bind((HOST, PORT))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]

print 'Socket bind complete'

#Start listening on socket
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!")


Node Client:

var net = require('net');

var client = new net.Socket();

client.connect(15000, 'localhost', function() {
    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);

Output of 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)

On the other hand, if i use a node server along with the same node client as above, the problem does not happen. The socket is closed once the client exits and i don't see any sockets left in the CLOSE_WAIT state.

Node Server:

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');



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

To summarize my issue:

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

Wondering why this is occurring and perhaps i may be missing something here. Any guidance is much appreciated.

Tested on local machine with python 2.7.12, node 8.9.2 and Ubuntu 16.04.03



answered 1 week ago ralphtheninja #1

You should use client.end() instead of client.destroy(). And also socket.end() on the server.

comments powered by Disqus