im doing some basic socket programming in python. But im having some trouble figuring out how my echoserver could notice that the echoclient has closed it’s connection, without a constant ping/pong or timeout.
echoclient.py
#echoclient
import sys
import socket
import os
import datetime
def log(s):
return datetime.datetime.now().strftime('%H:%M:%S') + ' - ' + s
s = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 9000))
while 1:
try:
foo = raw_input('what do you want to send?: ')
if len(foo) > 0:
s.send(foo)
except KeyboardInterrupt:
print 'shutting down connection'
s.close()
break
data = s.recv(1024)
if data:
print log('Recieved'), repr(data)
echoserver.py
#echoserver
import sys
import socket
import os
import datetime
def log(s):
return datetime.datetime.now().strftime('%H:%M:%S') + ' - ' + s
port = 9000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', port))
s.listen(5)
while 1:
conn, addr = s.accept()
conn.settimeout(10)
print 'Connected by', addr
while 1:
try:
data = conn.recv(1024)
if data:
print log(repr(data))
conn.send(data)
except KeyboardInterrupt:
print 'Closing connection ', addr
conn.close()
sys.exit(1)
except:
print 'Exception caught! closing connection ', addr
conn.close()
break
Now the only way the server knows that the client has died is by the conn.settimeout(10)
-
How can i get a exception for my server when the client disconnects preferably without a constat ping/pong message between them or settimeout.
-
My next step is to create a echoproxy between the echoclient and echoserver, will i need to use threads/multiprocessing to achieve this? Any tips or pointers?
-
Anything else you have to comment about bad/good practices is welcome
Thanks!
It was my understanding the socket library already gets a message when clients disconnect.
When the other ends disconnects abruptly (like a network fault or crash) that’s when the timeout comes into play.
In your server code above you should be able to immediately detect client disconnects using: