基于socketserver实现并发的socket套接字编程
并发:让服务端同时和多个客户端进行连接。使用socketserver的连接循环(并发),但是使用了自己的通信循环
服务端
import socketserver
print('start...')
class Myhandler(socketserver.BaseRequestHandler):
# 通信循环
def handle(self):
while True:
try:
cmd = self.request.recv(1024)
print('来自客户端数据:', cmd)
self.request.send(cmd.upper())
except ConnectionResetError:
break
if __name__ == '__main__':
server = socketserver.ThreadingTCPServer(('127.0.0.1', 8000), Myhandler, bind_and_activate=True)
server.serve_forever()
客户端1
from socket import *
client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8000))
while True:
client.send('cmd'.encode('utf8'))
data = client.recv(1024)
print(data.decode('gbk'))
客户端2
from socket import *
client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8000))
while True:
client.send('hello'.encode('utf8'))
data = client.recv(1024)
print('来自服务端的数据:',data.decode('gbk'))