【发布时间】:2020-01-21 17:43:48
【问题描述】:
我正在尝试在 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]
客户端代码:
#!/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))
【问题讨论】:
-
看起来你总是需要在终端中输入“时间”来保持连接,否则它会在任何其他输入时终止。这是您发送来测试的吗?