On Tue, Aug 27, 2013 at 5:45 AM, Paul Pittlerson <menkomig...@gmail.com> wrote: > I'm currently learning about the socket module. My question is how can I > detect if a connection is closed from the other side, for example a > KeyboardInterrupt as I frequently use. My code below: >
Once the remote end has terminated (as it will presumably do in this case), any attempt to write to the socket will eventually result in an error. You should be able to see that by simple experimentation. Be aware that it might take a bit of time for the error to filter back to you; it depends on whether the remote end actually sends back a RST (reset) packet or not. (In a sane system, hitting Ctrl-C should result in a clean shutdown and proper socket closure, but your server needs to handle the case where it doesn't get one.) Play around with it, you should be able to figure out what it's doing for you. A couple of tangential comments about your script: > ########################################################## > #server script: > > def decode(self, data): > return pickle.loads(data) MAJOR security issue here. You are taking data from a networked source and running it through a trusting system (pickle). This is NOT recommended. Also: You're using a stream socket, and depending - I think - on getting an entire message in a single read() call. This is definitely not guaranteed, though when you're working with localhost it's likely to be true. To make this reliable, you'll need to do something like prefix the message with its length (eg a Hollerith string), or use some system like JSON that lets you detect the end of the message. >From the client: > def loop(): > print 'Enter message:' > msg = raw_input() > encoded = pickle.dumps(msg) > connection.send(encoded) > loop() > > loop() Why recurse? Why not simply loop? No Python has tail-call optimization (as far as I know), so this will eventually blow up with a RuntimeError: maximum recursion depth exceeded. ChrisA -- http://mail.python.org/mailman/listinfo/python-list