Socketserver
概念
socketserver模块简化了编写网络服务器的任务。
Socketserver实现服务端与多个客户端交互
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| import socketserver
class MyServer(socketserver.BaseRequestHandler): def handle(self): while True: recv_msg = self.request.recv(1024).decode('utf-8') if recv_msg == 'q': self.request.send(b'q') break else: print(recv_msg) info = input('服务端 >>>').strip() if info: self.request.send(info.encode('utf-8'))
if __name__ == '__main__': server = socketserver.ThreadingTCPServer(('localhost', 8889), MyServer) server.allow_reuse_address = True server.serve_forever()
import socket
sk = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) sk.connect(('localhost', 8889)) while True: info = input('客户端 >>>').strip() if info == '': continue elif info == 'q': sk.send(info.encode('utf-8')) break else: sk.send(info.encode('utf-8')) recv_msg = sk.recv(1024).decode('utf-8') print(recv_msg) sk.close()
|