我试图用python编写一个客户机/服务器程序,它将接受多个连接并使用线程管理它们。服务器和客户机都在运行,客户机将收到来自服务器“processClient”函数的“欢迎”消息,这意味着正在建立连接并启动线程。但是,在收到欢迎消息之后,对连接对象的任何后续接收或发送都将失败,并出现“OSError:[Errno 9]Bad file descriptor”错误。我已经对这个错误做了一些搜索,大多数问题似乎都是由于有人试图使用之前关闭的套接字或连接而导致的,这里不应该出现这种情况。有人知道是什么导致了这个错误吗?运行python 3.5.2版
服务器代码:
#!/usr/bin/env python3
import socket
import sys
import os
import datetime
import threading
import random
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
def processClient(conn, id):
welcome = "Hello, you are client number " + str(id)
welcome = bytes(welcome, 'utf-8')
conn.sendall(welcome)
while True:
data = conn.recv(1024)
print(rpr(data))
time = str(datetime.datetime.now())
arr = bytes(time, 'utf-8')
if data == b'time':
conn.sendall(arr)
elif data == b'':
conn.close()
return
else:
temp = data.decode("utf-8")
temp = temp.upper()
temp = bytes(temp, 'utf-8')
conn.sendall(temp)
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except:
print("unable to create socket connection, shutting down.")
quit()
s.bind(('0.0.0.0', PORT))
s.listen()
sys.stdout.write("Server is running \n")
runningThreads = []
threadID = 0
while True:
conn, addr = s.accept()
with conn:
#conn.setblocking(False)
print('Connected by', addr)
threadID += 1
threadTemp = threading.Thread(target = processClient, args=(conn, threadID))
threadTemp.start()
runningThreads.append(threadTemp)
for t in runningThreads:
if not t.isAlive():
# get results from thtead
t.handled = True
threadID -= 1
else:
t.handled = False
runningThreads = [t for t in runningThreads if not t.handled]
客户代码:
^{pr2}$
对于其他偶然发现这个问题的人来说:我终于解决了这个问题。服务器在尝试从连接读取数据之前没有等待来自客户端的输入,这就触发了错误(错误消息对诊断此问题尤其没有帮助)。我重写了它以使用python选择器而不是线程选择器,选择器包含非常方便的轮询功能,可以用来“暂停”直到有数据要读取。我本可以自己把它构建到程序中,但是既然已经有一个语言特性可以为您实现这个功能,为什么还要这么做呢?在
相关问题 更多 >
编程相关推荐