我正在使用套接字创建一个 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()
谢谢,
约旦