我一直在尝试制作一个多客户端服务器,我终于拥有并且它运行良好,但我现在想做的是让客户端输入他们的名字,而不是获取客户端地址,然后程序会说“鲍勃:大家好”而不是“127.0.0.1:大家好”。
我使用了 python 文档中的预制服务器和客户端。这是服务器:
import socketserver
class MyUDPHandler(socketserver.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
name = self.request[0].strip()
socket = self.request[1]
print(name,"wrote:".format(self.client_address[0]))
print(data)
socket.sendto(data.upper(), self.client_address)
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
server = socketserver.UDPServer((HOST, PORT), MyUDPHandler)
server.serve_forever()
这是客户:
import socket
import sys
HOST, PORT = "localhost", 9999
data = "".join(sys.argv[1:])
name = "".join(sys.argv[1:])
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(bytes(name + "Bob", 'utf-8'), (HOST, PORT))
sock.sendto(bytes(data + "hello my name is Bob", "utf-8"), (HOST, PORT))
received = str(sock.recv(1024), "utf-8")
print("Sent: {}".format(data))
print("Received: {}".format(received))
一切正常,但由于某种原因,一旦客户端连接,我就会在服务器中得到它。
b'Bob' wrote:
b'Bob'
b'hello my name is bob' wrote:
b'hello my name is bob'
我希望它像:
Bob wrote:
b'Hello my name is bob'
我希望有人可以帮助我,谢谢。