Python网络编程——并发的SocketServer
1、并发的 socketserver
实现程序的并发执行
Server
import timefrom 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永远运行下去,除非强制停止程序
Client 1
import socketsk = socket.socket()
sk.connect(("127.0.0.1",9001))
while True:
ret = sk.recv(1024)
print(ret)
Client 2
import socketsk = socket.socket()
sk.connect(("127.0.0.1",9001))
while True:
ret = sk.recv(1024)
print(ret)
以上是 Python网络编程——并发的SocketServer 的全部内容, 来源链接: utcz.com/z/537746.html