使用 python 和线程的服务器-客户端聊天

server-client chat using python with threading

我正在尝试设置两个主机之间的命令提示符聊天。为了同时启用打字和打印,我使用 threading。使用以下代码将一台 PC 设置为服务器:

def recvfun():
    for i in range(5):
        print c.recv(1024)
    return

def sendfun():
    for i in range(5):
        c.send(raw_input())
    return

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port
s.listen(5)                 # Now wait for client connection.
c, addr = s.accept()     # Establish connection with client.
print 'Got connection from', addr

try:
    Thread(target = recvfun, args = []).start()
    Thread(target = sendfun, args = []).start()
except Exception,errtxt:
    print errtxt

c.close()                   # Close the connection

另一台电脑设置了类似的代码:

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
host = "192.168.1.111"
s.connect((host, port))

try:
    Thread(target = recvfun, args = []).start()
    Thread(target = sendfun, args = []).start()
except Exception,errtxt:
    print errtxt

s.close                     # Close the socket when done

目前我运行客户端和服务器在同一台机器上,有两个命令提示符。但是每当我尝试发送或接收文本时,我都会在服务器命令提示符下收到以下错误日志:

Got connection from ('192.168.1.111', 25789)
hi
Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 810, in __bootstrap_inner
    self.run()
  File "C:\Python27\lib\threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "C:\Python27\programs\server.py", line 12, in sendfun
    c.send(raw_input())
  File "C:\Python27\lib\socket.py", line 170, in _dummy
    raise error(EBADF, 'Bad file descriptor')
error: [Errno 9] Bad file descriptor

你们中的任何人都可以帮助我理解为什么我会收到此错误以及如何解决它。

感谢阅读!!!

线程启动并等待您输入代码,同时主程序继续运行并立即关闭套接字或连接,使其无法发送数据并导致错误。在关闭任何东西之前,您必须等待线程完成。您可以通过删除 close 调用来证明这一点。