|
v
+-----------+ +------------------+
| TCPServer |------->| UnixStreamServer |
+-----------+ +------------------+
|
v
+-----------+ +--------------------+
| UDPServer |------->| UnixDatagramServer |
- First, you must create a request handler class by subclassing the
BaseRequestHandler
class and overriding itshandle()
method; this method will process incoming requests. - Second, you must instantiate one of the server classes, passing it the server’s address and the request handler class.
- Then call the
handle_request()
orserve_forever()
method of the server object to process one or many requests. - Finally, call
server_close()
to close the socket.
BaseRequestHandler
class ,并且还要
重写父类里handle()方法;
import socketserver class MyServer(socketserver.BaseRequestHandler): def handle(self): # 创建一个链接,继承于socketserver中的BaseRequestHandler类 conn = self.request # 发送登录提示 conn.sendall(b"Welcome to login...") print("Client connect...") while True: print("Waitting for recving message...") # 接收消息 message = conn.recv(1024) print(message.decode('utf-8')) # 收到exit就退出 if message == "exit": break # 回复消息 data = input("Reply message:") # 发送消息 conn.sendall(data.encode('utf-8')) if __name__ == "__main__": # 实例化 server = socketserver.ThreadingTCPServer(('127.0.0.1', 999, ), MyServer) # 调用serve_forever方法 server.serve_forever() ''' def serve_forever(self, poll_interval=0.5): """ Handle one request at a time until shutdown. Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread. """ ''' multi_socketserver_client.py # 就是一个简单的TCP客户端 import socket sock = socket.socket() # 连接服务端 sock.connect(('127.0.0.1', 999, )) login = sock.recv(1024) print(login.decode('utf-8')) while True: message = input("Please input the message:").strip() if message == "exit": sock.sendall(b'exit') break else: sock.sendall(message.encode('utf-8')) print("Waitting for recving message...") data = sock.recv(1024) print(data.decode('utf-8')) sock.close()