Python实现一个服务端,多个客户端接入
1. 服务器端
服务器端每一次接收客户端连接,都要fork一个进程来完成,如果单纯使用socket模块来实现,是不容易完成多线程接入的。为了方便,可以直接使用socketserver
模块。
代码如下所示。
from socketserver import BaseRequestHandler, ThreadingTCPServer
class Handler(BaseRequestHandler):
def handle(self) -> None:
address, pid = self.client_address
print(f'{address} connected!')
while True:
data = self.request.recv(1024)
if len(data) <= 0:
print("close!")
break
print(f'receive data: {data.decode()}')
self.request.sendall('response'.encode())
if __name__ == '__main__':
server = ThreadingTCPServer(('127.0.0.1', 8998), Handler)
print("Listening")
server.serve_forever()
2. 客户端代码
import socket
class Client:
def __init__(self):
# ipv4 TCP
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self, server_ip, server_port):
self.client.connect((server_ip, server_port))
def run(self):
while True:
print("please input:")
message = input()
self.client.sendall(message.encode())
response = self.client.recv(1024)
print(response.decode())
if __name__ == '__main__':
client = Client()
client.connect('127.0.0.1', 8998)
client.run()
3. 运行效果
客户端1: 输入111
客户端2:输入222
服务器端: