Hi, all!

I was wondering if there is any way to check from the server side whether the client has closed a socket connected to one on my side.

client side

import socket
s = socket.create_connection ((host, random_port))
s.close ()

server side

...
a = lstn.accept ()

How can I check from the server side whether s is closed or not ?:-/
Sincerely, n.utiu!

A simple way to do this would be to try to send or recv information. If the client is no longer connected, you will get a socket.error with the message:

socket.error: [Errno 107] Transport endpoint is not connected

You can catch this in an except clause to work around it.
Hope this helps.

A simple way to do this would be to try to send or recv information. If the client is no longer connected, you will get a socket.error with the message:


You can catch this in an except clause to work around it.
Hope this helps.

I tried this. I shut the socket down with socket.shutdown (socket.SHUT_RDWR) and closed it, but I successfully send data with no exceptions raised and always receive a null string with recv.

??? Something is wrong here.

Can you show code to what you do?

You can't receive or send data through a socket if you properly closed it.


Cheers and Happy coding

Edited 6 Years Ago by Beat_Slayer: n/a

??? Something is wrong here.

Can you show code to what you do?

You can't receive or send data through a socket if you properly closed it.


Cheers and Happy coding

server

import socket 
lstn = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
lstn.bind (('', 2727))
lstn.listen (1)

(a, b) = lstn.accept ()
a.setblocking (0) # i use it with non blocking 

while True:
  try:
    a.recv (1)
  except socket.error, (value, msg):
    if value != 11: # it's not the Service unavailable exception
      raise

client

import socket
s = socket.create_connection (('localhost', 2727))
s.shutdown (socket.SHUT_RDWR)
s.close ()

And it works ! T_T
I don't get any exception.

Whats your line 6?

And shouldn't you have

lstn.recv(1)

Cheers and Happy coding

Edited 6 Years Ago by Beat_Slayer: n/a

As Beat_Slayer said, you won't have any problems receiving information FROM the client. Why would you, if it is still open and sending? If the socket were closed in this case it would likely just wait into infinity (enter threaded handling).
By checking if you can SEND information, you will see if the connection is still established immediately. Thus, if the connection is not open, the exception socket.error will be raised.

Thanks, I fixed it! Hooray!
Also in the meantime I decided to start using SocketServer.

Sincerely, n.utiu.

This question has already been answered. Start a new discussion instead.