在线程/进程之间传递套接字连接n python(多处理)

时间:2016-03-21 13:20:11

标签: python multithreading sockets multiprocessing

我正在准备新的驱动程序(应该通过TCP / IP工作),我遇到了一些问题。

主要思想是,将有两个独立的循环。

  1. 循环绑定端口并继续侦听传入的连接请求。一旦请求被接受,它授权客户端,如果获得授权,则将其连接传递给第二个循环。客户端传递到第二个循环后,它应继续监听传入的连接。如果新客户端连接,则将其传递给第二个循环,依此类推..
  2. 第二个循环接受连接的客户端,并管理与他的发送和接收数据。但是,它还检查是否没有新连接,如果是,它将关闭与客户端的实际连接并使用新连接。
  3. 这应该确保如果客户端连接丢失,我们不必等待超时来获得新连接(这就是我创建这个新驱动程序的原因)。如果激活了新连接,我们只需关闭旧连接并继续与调制解调器通信,缩短时间。

    这是代码(简化):

    class SocketDriver(Process):
    
    def __init__(self):
        Process.__init__(self)
        self.stop_event = Event()
        self.client = None
        self.addr = None
        self.client_queue = Queue()
    
    def connection_manager(self):
        while not self.stop_event.is_set():
            try:
                log.info('Binding to %s on port: %s' % (self.atmel_name, self.port))
                self.socket_object.bind((self.ip, self.port))
                break
            except socket.error, e:
                if e.errno == errno.EADDRINUSE:
                    log.error('Socket error: %s, re-trying' % e)
                    time.sleep(5)
                else:
                    log.exception('Unknown exception')
                    break
    
        while not self.stop_event.is_set():
            self.socket_object.listen(5)
            log.info('Waiting for incoming connections')
            # This cannot be touched, because accept command wont pass until something connect
            client, addr = self.socket_object.accept()
            log.info('Accepted connection from %s:%s' % (addr[0], addr[1]))
            self.client_queue.put([client, addr])
    
    def open(self, port, bootloader=False):
        """
        Open port and load drivers
        """
        self.socket_object = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
        #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
        start_new_thread(self.connection_manager ,())
    
    def run(self):
        """
        Loop throught FIFO structures, check for incomming packet,
        send to peripheral device, receive response and deliver it
        """
        log.info('Starting SocketDriver loop')
    
        while not self.stop_event.is_set():
            # Watchdog touch
            open(touchfile, 'w').close()
    
            #Check if there is new client available
            if not self.client_queue.empty():
                log.info('New client found!')
                if self.client != None:
                    self.client.close()
                conn_data = self.client_queue.get()
                self.client = conn_data[0] 
                self.addr = conn_data[1]
                log.info('Connected to new client with address: %s:%s' % (self.addr[0], self.addr[1]))
    
            # Check if there is any new connection
            if self.client != None:
                log.info('Client found, checking queues')
                for out_queue, in_queue, driver_id in self.fifocom_list:
    
                    while not self.stop_event.is_set():
                        if not out_queue.empty():
                            self.write_packet(atmel_packet, driver_id)
    
                        # Vycitame a spracujeme odpoved
                        ready = select.select([self.client], [], [], 1)
                        if ready[0]:
                            log.info('[%s] Reading', self.source_name)
                            atmel_packet = self.read_packet()
    
            time.sleep(0.1)
    

    基本思想是在与实际连接的客户端通信时继续侦听新连接。

    然而,当我把任何其他内容放入“self.client_queue”时,“if not self.client_queue.empty():”工作。但是,当我把“self.socket_object.accept()”中的客户端和地址放在那里时,它会粉碎:

    Traceback (most recent call last):
        File "/usr/lib/python2.7/multiprocessing/queues.py", line 266, in _feed
            send(obj)
    TypeError: expected string or Unicode object, NoneType found
    

    有人可以解释一下这里发生了什么吗?我已经读过在进程之间移动已打开的社交存在问题,但该线程正在一个进程中运行。

0 个答案:

没有答案