如何修复多处理回显服务器以处理多个客户端

时间:2019-01-11 05:40:49

标签: python multithreading sockets python-multiprocessing

我想创建一个多处理回显服务器。我目前正在使用telnet作为客户端将消息发送到我的回显服务器。当前,我可以处理一个telnet请求,它会回显响应。最初,我以为每次创建套接字时都应该初始化pid。正确吗?

如何允许多个客户端使用多重处理连接到我的服务器。

#!/usr/bin/env python
import socket
import os
from multiprocessing import Process

def create_socket():

    # Create socket
    sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Port for socket and Host
    PORT = 8002
    HOST = 'localhost'

    # bind the socket to host and port
    sockfd.bind((HOST, PORT))
    # become a server socket
    sockfd.listen(5)

    start_socket(sockfd)

def start_socket(sockfd):

    while True:

        # Establish and accept connections woth client
        (clientsocket, address) = sockfd.accept()

         # Get the process id.
        process_id = os.getpid()
        print("Process id:", process_id)

        print("Got connection from", address)
        # Recieve message from the client
        message = clientsocket.recv(2024)
        print("Server received: " + message.decode('utf-8'))
        reply = ("Server output: " + message.decode('utf-8'))
        if not message:
            print("Client has been disconnected.....")
            break
        # Display messags.
        clientsocket.sendall(str.encode(reply))

    # Close the connection with the client
    clientsocket.close()

if __name__ == '__main__':

    process = Process(target = create_socket)     
    process.start()

2 个答案:

答案 0 :(得分:1)

了解哪些阻止系统调用,哪些不阻止系统调用可能是一个好主意。例如,listen没有阻止,而accept正在阻止一个。因此,基本上-您通过Process(..)创建了一个进程,该进程在accept处阻塞,并且在建立连接时-处理该连接。

您的代码应具有结构-类似于以下内容(伪代码)


def handle_connection(accepted_socket):
    # do whatever you want with the socket
    pass

def server():

    # Create socket and listen to it. 
    sock = socket.socket(....)
    sock.bind((HOST, PORT))
    sock.listen(5)

    while True:
        new_client = sock.accept() # blocks here.

        # unblocked 
        client_process = Process(target=handle_connection, args=(new_client))
        client_process.start()

我还必须提到,虽然这是仅了解如何完成工作的好方法,但为每个连接启动一个新的过程并不是一个好主意。

答案 1 :(得分:0)

设置服务器,绑定,监听等(您的create_socket)的初始部分应该在主进程中。

一旦accept并获得一个套接字,就应该生成一个单独的进程来处理该连接。换句话说,您的start_socket应该在单独的过程中产生,并且应该永远循环。