0

My TCP server is written in Node.js. In Node.js there is a close event to handle socket closure. So a simple node.js socket code will be like this, copy from the official document.

const net = require('node:net');
const client = net.createConnection({ port: 8124 }, () => {
  // 'connect' listener.
  console.log('connected to server!');
  ...
});
client.on('data', (data) => {
  //receive data
});
client.on('end', () => {
  console.log('disconnected from server');
}); 

I have some tcp client code written in Python. But to my surprise, I can't find the equivalent close event handler, my Python script like this,

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 8124)
try:
    data = sock.recv(1024)
except ConnectionResetError:
    print("ConnectionResetError closed by peer")
except socket.error as e:
    print("socket.error closed by peer")
except Exception as e:
    print("Exception closed by peer")

I had thought the close event will be handled either in ConnectionResetError or socket.error but when Node.js server closes the socket, none of those except codes are called. The Python program just jumps out of the try block and runs the next line after that.

So how do I handle the close event in my python script?

---- update ----

With the answer I got I also found these similar questions. Coming from Node.js background I had thought there would be a straightforward way as Node.js provides.

  1. python sockets: how to detect that client has closed/disconnected from the server side

  2. How to know the if the socket connection is closed in python?

  3. Python: detect when a socket disconnects for any reason?

Qiulang
  • 10,295
  • 11
  • 80
  • 129

1 Answers1

1

recv() returns zero bytes on socket close, so in your case you can use if not data: to detect closure.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • Thanks! With your answer I also found this Q&A https://stackoverflow.com/questions/28018799/python-sockets-how-to-detect-that-client-has-closed-disconnected-from-the-serve . The Node.js's way quite straightforward, I didn't realize it would be such a convoluted way in python. – Qiulang Jul 07 '23 at 13:32
  • @Qiulang In Python `socket` is a very thin layer over the C APIs of the same name. That’s the way those APIs work and I’m sure Node.js is using the same APIs in its implementation. – Mark Tolonen Jul 07 '23 at 16:25