一、说明socketserver
SocketServer内部使用 IO多路复用 以及 “多线程” 和 “多进程” ,从而实现并发处理多个客户端请求的Socket服务端。即:每个客户端请求连接到服务器时,Socket服务端都会在服务器是创建一个“线程”或者“进 程” 专门负责处理当前客户端的所有请求。
二、socketserver 实例
服务器端:
#!/usr/bin/env python #-*- coding:utf-8 -*- import socketserver class MyTcpHandler(socketserver.BaseRequestHandler): def handle(self): while True: print("New conn:",self.client_address) data = self.request.recv(1024) if not data: break print("client says:",data.decode()) self.request.send(data) if __name__ == "__main__": HOST,PORT = "127.0.0.1",57000 server = socketserver.ThreadingTCPServer((HOST,PORT),MyTcpHandler) server.serve_forever()
客户端:
#!/usr/bin/env python #-*- coding:utf-8 -*- import socket IpPort = (‘127.0.0.1‘,57000) Fsk = socket.socket() Fsk.connect(IpPort) while True: Msg = input("client>>").strip() Fsk.sendall(bytes(Msg,"utf8")) ServerReplay = Fsk.recv(1024) print("Server",str(ServerReplay,‘utf8‘)) Fsk.close()
运行服务器端
C:\Users\AppData\Local\Programs\Python\Python36-32\python.exe D:/py_pro/s12/day08/LearnSocketserver.py New conn: (‘127.0.0.1‘, 65418) client says: hi New conn: (‘127.0.0.1‘, 65418) client says: hhh New conn: (‘127.0.0.1‘, 65418) New conn: (‘127.0.0.1‘, 65433) client says: lakaka New conn: (‘127.0.0.1‘, 65433) client says: m New conn: (‘127.0.0.1‘, 65418)
运行客户端:
C:\Users\AppData\Local\Programs\Python\Python36-32\python.exe D:/py_pro/s12/day08/SocketServerClient.py client>>hi Server hi client>>hhhm Server hhh client>>m Server m client>>
时间: 2024-11-20 23:40:23