1

我正在编写 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)
......
4

1 回答 1

1

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

绑定一次socket,然后进入循环等待客户端:

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)                
于 2012-11-17T20:30:18.927 回答