0

I am creating a Python Server/Client chat program (like AOL instant messenger) using sockets. I run into a problem when I force quit the server or the client because my socketInstance.recv() method is sent a huge amount of "" blank strings. I am wondering how to run a closing method, like a deconstructor, when the cmd window is force quit so I can exit gracefully.

I've included my code, just in case (shouldn't be necessary tho):

Echo server program

import socket
import sys
import time


HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s = socket.socket()         # Create a socket object
HOST = socket.gethostname() # Get local machine name
print "Socket hostname: ", HOST
s.bind((HOST, PORT))
conn = None


def check_for_messages():
    print 'Check for messages...'
    global conn
    while 1:
        try:
            data = conn.recv(1024)
            if not data: break
            conn.sendall(data)
            print data
        except socket.error:
            #[Errno 10054] Client Closes
            pass


    print "END OF CHECK MESS"


def check_for_client():
    print 'Listening...'
    global conn
    s.listen(1)
    conn, addr = s.accept()
    print 'Connected by', addr

check_for_client()
check_for_messages()

Echo client program

import threading
import socket
import time
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = socket.gethostname()    # The local host
s.connect((HOST, PORT))

getUserInputThread = None
getMessThread = None
receivedMessages = []

def getMessage():
    print "getMessageThread running"
    while 1:
        data = s.recv(1024)
        if not data: 
            print "OVERLORD: Possible server disconnect"
            break
        receivedMessages.append(data)

    print "getMessageThread ending\n"

def getUserInput():
    print "getUserInputThread running"
    while 1:
        message = raw_input("type: ")
        s.sendall(message)

        #print messages in list:
        while len(receivedMessages) > 0:
            print "Received Messages Length: %d" % len(receivedMessages)
            print receivedMessages.pop(0)

    print "getUserInputThread ending"

getUserInputThread = threading.Thread(target=getUserInput)
getUserInputThread.start()
getMessThread = threading.Thread(target=getMessage)
getMessThread.start()

Thanks,

Jordan

1 Answer 1

1

You could use the atexit module to perform final cleanup before terminating:

import atexit

@atexit.register
def do_cleanup():
    print "doing some cleanup..."
    #close sockets, put chairs on tables, etc
    print "goodbye"

#loop forever, until the user hits ctrl-c
while True:
    pass

Result:

C:\Users\kevin\Desktop>test.py
Traceback (most recent call last):
  File "C:\Users\kevin\Desktop\test.py", line 12, in <module>
    while True:
KeyboardInterrupt
doing some cleanup...
goodbye

This will work if your user force quits with a KeyboardInterrupt, but not if he closes the command window with the X button, terminates the task with task manager, unplugs the computer, etc.

1
  • Strangely enough, KeyboardInterrupt doesn't actually end the program for me, I assume its because I'm running multiple threads?
    – Jordan
    Commented Jun 19, 2013 at 20:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.