错误的文件描述符python套接字

时间:2018-08-22 07:11:02

标签: python multithreading sockets server

im试图使udp服务器仅接受数据,而不接收回客户端,而我遇到了这个问题,并且我不知道是什么原因导致了错误的文件描述符,这是服务器代码:

import threading
import socket
import logging

class Broker():

    def __init__(self):
        logging.info('Initializing Broker')
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind(('', 6668))
        self.clients_list = []

    def talkToClient(self, ip):
        #logging.info("Sending 'ok' to %s", ip)

        print ("Buat Thread Baru")

        while True:
            try:
                data = self.sock.recv(1024)
                if data:
                    # Set the response to echo back the recieved data 
                    response = data
                    self.sock.send(response)
                else:
                    raise error('Client disconnected')
            except:
                self.sock.close()
                return False


            self.sock.sendto("ok", ip)


    def listen_clients(self):
        while True:
            msg, client = self.sock.recvfrom(1024)
            self.sock.settimeout(20)
            logging.info('Received data from client %s: %s', client, msg)
            t = threading.Thread(target=self.talkToClient, args=(client,))
            t.start()

if __name__ == '__main__':
    # Make sure all log messages show up
    logging.getLogger().setLevel(logging.DEBUG)

    b = Broker()
    b.listen_clients()

1 个答案:

答案 0 :(得分:1)

UDP是无连接的,因此在您的线程代码中永远不会发生错误Client disconnected。但是对于任何其他错误(在您的情况下,可能是socket.timeout),套接字已关闭。随后,在您的主程序中出现bad filedescriptor错误。

如果要在线程中超时,则需要打开一个新的套接字。而且,您还必须向客户端发送问候消息,以便他知道用于一对一通信的新端口。

还请注意:UDP不可靠。