Python socket +守护进程在发送数据后停止

时间:2012-11-17 20:10:55

标签: python sockets daemon

我正在编写python守护进程,它等待请求并返回一些数据。但是,当客户端请求脚本时,守护程序停止了它的工作。 这是代码

......
def run(self):
    while True:
        server_socket  = socket.socket()         # Create a socket object
        host = socket.gethostname() # Get local machine name
        port = 12345                # Reserve a port for your service.
        server_socket .bind((host, port))        # Bind to the port
                server_socket .listen(5)   

        client_socket, address  = server_socket.accept()    
 # Establish connection with client.

        print 'Got connection from', address 
        logging.info(address)
        #data = client_socket.recv(2048) 
        data = client_socket.recv(1024)
        logging.info(data)
......

1 个答案:

答案 0 :(得分:1)

我不确定您真正希望成为服务器功能,但根据您的示例,您拥有的是一台可以一次接受和处理一个客户端的服务器。我建议的不是每次连接后每次重新绑定服务器。没有必要。

将套接字绑定一次,然后进入循环等待客户端:

def run(self):
    server_socket = socket.socket()         
    host = socket.gethostname() 
    port = 12345               
    server_socket.bind((host, port))        
    server_socket.listen(5)   

    while True:
        # this will block until a client tries to connect
        client_socket, address  = server_socket.accept()    

        print 'Got connection from', address 
        logging.info(address)
        # this will block until data is received from client
        data = client_socket.recv(1024)
        logging.info(data)

这里会发生什么是服务器将接受客户端,然后在等待客户端发送内容时阻塞。然后它将再次循环等待新客户端。如果它是一次性连接并且您已完成处理,您甚至可能想要关闭该套接字。

如果您希望能够同时处理多个客户端,那么您将在主线程中执行循环,然后将每个新连接传递给工作线程以处理通信。这将释放主线程以继续循环并等待新客户端连接。

这可以通过为每个客户端启动一个全新的线程并传递套接字,或者使用在运行的线程的固定池之间共享的Queue来实现。每个线程都在等待从队列中提取项目,然后进入套接字项目的通信循环。完成后,它会回到队列中等待。

伪代码可能看起来像这样:

socket_queue = Queue()
...
def main_server_thread():
    while True:
        # this will block until a client tries to connect
        client_socket, address  = server_socket.accept()    

        print 'Got connection from', address 
        logging.info(address)

        # this will finish right away and loop again
        socket_queue.put(client_socket)
...
def client_worker_thread():
    while True:
        sock = socket_queue.get()
        while sock is still connected:
            data = sock.recv(1024)
            logging.info(data)