我正在用Python编写一个服务器,客户端将通过命令行arg发送命令"BYE"。此时应终止客户端/服务器之间的连接。(我认为socket.close()会终止连接,但我不完全确定这是否正确)
我编写了一个经过调整的echo服务器,其中clientsocket.close()位于服务器迭代的末尾。我希望只有收到BYE时才会出现这种情况。
我不确定我的服务器程序的结构是否导致了这个问题(我还没有使用getopt,因为我仍然需要弄清楚)
服务器:
from multiprocessing import Process
import socket
import os
def handler(clientsocket, clientaddr):
print "Accepted connection from: ", clientaddr
while 1:
data = clientsocket.recv(1024)
if data:
if data == "BYE":
print "recvd BYE"
clientsocket.send("BYE")
clientsocket.close()
# p.join()
elif data == "DIR":
print "recvd DIR"
DIR = os.getcwd()
clientsocket.send(DIR)
print "data recieved:"
print data
msg = "You sent me: %s" % data
clientsocket.send(msg)
clientsocket.close()
return
if __name__ == "__main__":
TCP_IP = '127.0.0.1'
TCP_PORT = 5004
BUFFER_SIZE = 1024
print 'socket()'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'bind()'
s.bind((TCP_IP, TCP_PORT))
# f = open('recv.txt', 'wb')
print 'listen()'
s.listen(5)
workerProcesses =[]
while 1:
print "Server is listening for connectionsn"
clientsocket, clientaddr = s.accept()
p = Process(target=handler, args = (clientsocket, clientaddr))
p.start()
# p.join()
workerProcesses.append(p)
serversocket.close()
当我把我的clientsocket.close()放在if"BYE"语句中时,我得到了错误:坏的套接字描述符。服务器的输出为:
data recieved:
BYE
Process Process-1:
Traceback (most recent call last):
File "/usr/lib64/python2.6/multiprocessing/process.py", line 232, in _bootstrap
self.run()
File "/usr/lib64/python2.6/multiprocessing/process.py", line 88, in run
self._target(*self._args, **self._kwargs)
File "pyServ.py", line 26, in handler
clientsocket.send(msg)
File "/usr/lib64/python2.6/socket.py", line 167, in _dummy
raise error(EBADF, 'Bad file descriptor')
error: [Errno 9] Bad file descriptor
有什么关于为什么会发生这种事的想法吗?
在handler()函数中,您有这样的:
if data == "BYE":
print "recvd BYE"
clientsocket.send("BYE")
clientsocket.close()
#p.join()
elif data == "DIR":
print "recvd DIR"
DIR = os.getcwd()
clientsocket.send(DIR)
print "data recieved:"
print data
msg = "You sent me: %s" % data
clientsocket.send(msg)
clientsocket.close()
return
如果是data == "BYE"
,则发送"BYE"并关闭套接字。。。然后打印"收到的数据"(打字错误):)
然后在if
语句中调用close()
。在if
语句之外,您将尝试在刚刚关闭的套接字上再次send()
数据。关闭套接字后,文件句柄将不再有效。你需要修改你的代码,这样你就不会在一个封闭的套接字上发送。。。我认为有两种明显的方式。
应该是
if data == "BYE":
print "recvd BYE"
clientsocket.send("BYE")
clientsocket.close()
#p.join()
elif data == "DIR":
print "recvd DIR"
DIR = os.getcwd()
clientsocket.send(DIR)
print "data recieved:"
print data
return
或
删除if
语句中对clientsocket.close()的调用