gpt4 book ai didi

Python 多处理/套接字 - 错误的文件描述符

转载 作者:行者123 更新时间:2023-12-01 04:18:24 24 4
gpt4 key购买 nike

我正在用Python编写一个服务器,客户端将发送命令(通过命令行arg)“BYE”。此时客户端/服务器之间的连接应终止。 (我认为 socket.close() 会终止连接,但我不完全确定这是否正确)

我编写了一个改编的回显服务器,其中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 connections\n"
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

if data == "BYE" 然后你发送“BYE”并关闭你的套接字...然后你打印“data receive”(打字错误):)

然后在 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() 的调用

关于Python 多处理/套接字 - 错误的文件描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34034398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com