2

I am working on socket programming and I have to keep the track of all the clients that join the server.

So I am just keeping them an list:

client = []

and appending the client to it whenever they connect to the server. Now, I have to remove the client from the list whenever the client disconnects. The trouble is how can a server know if a client has disconnected from that server.

For connecting server, I am using:

s = socket.socket()
s.bind((host, port))
client = []
while True:
   c, addr = s.accept()
   client.append(addr)
s.close()
CristiFati
  • 38,250
  • 9
  • 50
  • 87
lal rishav
  • 549
  • 3
  • 5
  • 17
  • If you used the accepted socket, you would get an error when writing, or a 0 byte read when reading as soon as peer has closed its sockect. – Serge Ballesta Apr 03 '17 at 07:42
  • On _Ux_ since (plain) sockets are file descriptors, you could use [`fcntl(fd, F_GETFD)`](http://man7.org/linux/man-pages/man2/fcntl.2.html). – CristiFati Apr 03 '17 at 07:52

1 Answers1

2

Normally, when a socket is disconnected, it raises a socket.error if written to, and also returns b"" when read from.

So what you can do is, you can catch that exception and remove the client if writing to, and check if the data is empty if reading from.

Btw, you need to use the socket as the client, not its addr.

Like this:

try:
    sock.send(data)
except socket.error:
    client.remove(sock)

data = sock.receive(1024)
if not data:
    sock.close()
    client.remove(sock)
noteness
  • 2,440
  • 1
  • 15
  • 15