我正在尝试用python编写一个客户机/服务器程序,它将接受多个连接并使用线程来管理它们。服务器和客户端都在运行,客户端将收到来自服务器"processClient“函数的”欢迎“消息,这意味着连接正在建立,线程正在启动。但是,欢迎消息之后在connection对象上的任何后续接收或发送都会失败,并出现"OSError: Errno9Bad 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]客户端代码:
#!/usr/bin/env python3
import socket
import sys
import os
import datetime
HOST = 0
while HOST == 0 or HOST == "":
HOST = input("Please enter host IP: ")
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
data = s.recv(1024)
print(repr(data))
while True:
inputString = input("Please input a string: ")
temp = bytes(inputString, 'utf-8')
s.sendall(temp)
if inputString == "":
quit()
data = s.recv(1024)
if data:
print(rpr(data))发布于 2019-09-26 23:31:03
对于其他偶然发现这个问题的人:我确实最终解决了这个问题。服务器在尝试从连接读取数据之前没有等待来自客户端的输入,这将触发错误(错误消息在诊断此问题时尤其没有帮助)。我重写了这段代码,使用python选择器而不是线程-选择器包含了非常方便的轮询功能,可以用来“暂停”,直到有数据要读取。我可以自己在程序中构建这个,但是当已经有一个语言特性可以为你做这个的时候,为什么要这样做呢?
https://stackoverflow.com/questions/58032200
复制相似问题