0

我正在使用套接字创建一个 Python 服务器/客户端聊天程序(如 AOL 即时通讯程序)。当我强制退出服务器或客户端时遇到问题,因为我的 socketInstance.recv() 方法发送了大量的“”空白字符串。 我想知道当cmd窗口强制退出时如何运行关闭方法,如解构函数,以便我可以优雅地退出。

我已经包含了我的代码,以防万一(不应该是必要的):

回声服务器程序

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 客户端程序

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()

谢谢,

约旦

4

1 回答 1

1

您可以在终止之前使用atexit模块执行最终清理:

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

结果:

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

如果您的用户使用 强制退出,这将起作用KeyboardInterrupt,但如果他使用 X 按钮关闭命令窗口,使用任务管理器终止任务,拔下计算机等,则不会。

于 2013-06-19T19:56:29.057 回答