想学学python网络编程,按书上写了两个服务器和客户端小程序,结果发现报错:
Traceback (most recent call last):
File "./tsTserv.py", line 20, in <module>
data = tcpCliSock.recv(BUFSIZ)
File "/usr/lib/python2.6/socket.py", line 165, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
服务器端部分源代码如下:
while True:
print 'waiting for connection...'
tcpCliSock,addr = tcpSerSock.accept()
print '...connected from:',addr
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
tcpCliSock.send('[%s] %s' %(ctime(),data))
tcpCliSock.close()
tcpSerSock.close()
解决方法:
tcpCliSock.close()被放到了第二个while循环里,导致接收一次数据后tcpCliSock就会被关闭,应将该语句放到外层循环里