"多客户端处理的多进程回声服务器修复方法"

2024-09-28 22:23:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个多处理回显服务器。我目前正在使用telnet作为我的客户端向echo发送消息服务器。当前我可以处理一个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()

Tags: andthefromimport服务器clientidmessage
2条回答

了解哪些阻塞系统调用,哪些不阻塞系统调用可能是个好主意。^例如,{}不是阻塞的,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()

我还必须提到,虽然这是一个很好的方式来理解事情可以如何做,但它不是一个好主意,开始一个新的过程,为每一个连接。你知道吗

设置服务器、绑定、侦听等(您的create_socket)的初始部分应该在主进程中。你知道吗

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

相关问题 更多 >