【问题标题】:Python socket connection error: OSError: [Errno 9] Bad file descriptorPython套接字连接错误:OSError:[Errno 9]错误的文件描述符
【发布时间】: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))

【问题讨论】:

  • 看起来你总是需要在终端中输入“时间”来保持连接,否则它会在任何其他输入时终止。这是您发送来测试的吗?

标签: python sockets


【解决方案1】:

对于其他偶然发现这一点的人:我终于解决了这个问题。服务器在尝试从连接中读取数据之前没有等待来自客户端的输入,这会触发错误(错误消息对于诊断此问题特别没有帮助)。我重写了这个以使用 python 选择器而不是线程选择器包括非常方便的轮询功能,可用于“暂停”直到有数据要读取。我本可以自己将它内置到程序中,但是既然已经有一个语言功能可以为你做这件事,为什么还要这样做呢?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 2019-03-24
    相关资源
    最近更新 更多