python中的forking服务器

2024-10-01 09:25:48 发布

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

我用python3编写了一个可以接受许多客户机的forking服务器(我没有设置客户机数量的限制)。每个客户机将按照与服务器的连接顺序在服务器中分配一个索引值。例如,第一个客户机将被称为客户机1,第二个客户机是客户机2,依此类推。在

但问题是这个索引没有正确地分配给客户机。请帮我解决这个问题。我正在发送服务器和客户端的python代码以及示例输出

对于服务器,代码是

import os, socket

host="127.0.0.1"
port=7000
s=socket.socket()
s.bind((host, port))
s.listen(10)

def handle_client(s, addr, i):
    while True:
        data=s.recv(1024)
        decoded_data=data.decode("utf-8")
        if not decoded_data:
                print("\nconnection with client " + str(i) + " broken\n")
                break
        print("  CLIENT " + str(i) + " -> " + decoded_data)

def server():
    i=1
    while i<=10:
        c, addr=s.accept()
        child_pid=os.fork()
        if child_pid==0:
                print("\nconnection successful with client " + str(i) + str(addr) + "\n")
                handle_client(c, addr, i)
        else:
                i+=1

server()

对于客户来说,代码是

^{pr2}$

现在我打开两个终端,在一个终端上运行服务器,在另一个终端上我逐个运行客户机

我运行客户端的终端是这样的

debesh@laptop:~/Documents/programs/python/network$ python3 forking_chat_client.py

 -> hii

 -> q
debesh@laptop:~/Documents/programs/python/network$ python3 forking_chat_client.py

 -> hello

 -> q
debesh@laptop:~/Documents/programs/python/network$ python3 forking_chat_client.py

 -> hii how are you???

 -> q
debesh@laptop:~/Documents/programs/python/network$ python3 forking_chat_client.py

 -> good day

 -> q
debesh@laptop:~/Documents/programs/python/network$ 

运行服务器的终端是这样的

debesh@laptop:~/Documents/programs/python/network$ python3 forking_chat_server.py

connection successful with client 1('127.0.0.1', 50362)

  CLIENT 1 -> hii

connection with client 1 broken


connection successful with client 2('127.0.0.1', 50363)

  CLIENT 2 -> hello

connection with client 2 broken


connection successful with client 1('127.0.0.1', 50364)

  CLIENT 1 -> hii how are you???

connection with client 1 broken


connection successful with client 3('127.0.0.1', 50365)

  CLIENT 3 -> good day

connection with client 3 broken

正如您在服务器终端中看到的,索引1被分配给两个客户机第一个和第三个。这是怎么发生的?我的代码有什么毛病?请帮帮我


Tags: 服务器client终端data客户机withnetworkconnection
1条回答
网友
1楼 · 发布于 2024-10-01 09:25:48

问题是,分叉进程在处理客户机之后继续运行服务器循环。在调用handle_client(c, addr, i)之后尝试添加break

def server():
    i=1
    while i<=10:
        c, addr=s.accept()
        child_pid=os.fork()
        if child_pid==0:
                print("\nconnection successful with client " + str(i) + str(addr) + "\n")
                handle_client(c, addr, i)
                break                                 # fix here!
        else:
                i+=1

相关问题 更多 >