簡體   English   中英

Python 套接字連接錯誤:OSError: [Errno 9] 錯誤的文件描述符

[英]Python socket connection error: OSError: [Errno 9] Bad file descriptor

我正在嘗試在 python 中編寫一個客戶端/服務器程序,它將接受多個連接並使用線程管理它們。 服務端和客戶端都運行,客戶端會收到來自服務端“processClient”function的“歡迎”消息,表示正在建立連接,正在啟動線程。 但是,在歡迎消息失敗后,連接 object 上的任何后續接收或發送都會出現“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 選擇器而不是線程選擇器包括非常方便的輪詢功能,可用於“暫停”直到有數據要讀取。 我本可以自己將它內置到程序中,但是當已經有一個語言功能可以為你做這件事時,為什么要這樣做呢?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM