使用带有线程

时间:2016-04-09 19:05:13

标签: python multithreading python-2.7 python-multithreading

我正在尝试在两台主机之间设置命令提示符聊天。要同时启用打字和打印,我正在使用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

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

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

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

感谢您阅读!!!

1 个答案:

答案 0 :(得分:1)

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