1、并发的 socketserver
实现程序的并发执行
Server
import time
from socketserver import BaseRequestHandler,ThreadingTCPServer
# BaseRequestHandler 基础请求操作符
# ThreadingTCPServer 线程实现的基于tcp协议的server
class Myserver(BaseRequestHandler): # 创建一个Myserver类继承BaseRequestHandler
def handle(self):
n = 0
while True:
self.request.send(str(n).encode('utf-8')) # self.request == conn(server的IP)
n += 1
time.sleep(0.5)
server = ThreadingTCPServer(('127.0.0.1',9001),Myserver) # 创建一个server将服务地址绑定到127.0.0.1:9001
server.serve_forever() # 让server永远运行下去,除非强制停止程序
ThreadingTCPServer源码的继承关系梳理
Client 1
import socket
sk = socket.socket()
sk.connect(('127.0.0.1',9001))
while True:
ret = sk.recv(1024)
print(ret)
Client 2
import socket
sk = socket.socket()
sk.connect(('127.0.0.1',9001))
while True:
ret = sk.recv(1024)
print(ret)