我已经使用python 3编写了一个将接受许多客户端的分叉服务器(我没有设置客户端数量的限制)。将按服务器连接的顺序为每个客户端分配服务器中的索引值。例如,第一个客户端将被称为客户端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()
对于客户端,代码是
import socket
def client():
host="127.0.0.1"
port=7000
s=socket.socket()
s.connect((host, port))
msg=str(input("\n -> "))
encoded_msg=bytes(msg, "utf-8")
while msg!='q':
s.send(encoded_msg)
msg=str(input("\n -> "))
encoded_msg=bytes(msg, "utf-8")
client()
现在我打开2个终端并在一个终端中运行服务器,然后逐个运行客户端
我运行客户端的终端就是这样
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被分配给两个客户端 - 第一个和第三个客户端。这是怎么发生的?什么是我的代码中的错误?请帮帮我
答案 0 :(得分:1)
问题是您的分叉进程在处理客户端后继续运行服务器循环。在致电break
后尝试添加handle_client(c, addr, i)
:
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