socketserver实现并发
作者:互联网
socketserver实现并发
tcp服务端
import socketserver
class MyRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
while True:
try:
data = self.request.recv(1024) # 最大接收的字节数
if len(data) == 0:
break
print(data)
self.request.send(data.upper())
except Exception:
break
self.request.close()
server = socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyRequestHandler,bind_and_activate=True)
server.serve_forever()
tcp客户端
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 8080))
while True:
msg = input('>>>: ').strip()
if len(msg) == 0:
continue
client.send(msg.encode('utf-8'))
data = client.recv(1024)
print(data.decode('utf-8'))
client.close()
基于tcp的socketserver我们自己定义的类中的
- self.server即套接字对象
- self.request即一个链接
- self.client_address即客户端地址
udp客户端
import socketserver
class MyRequestHanlder(socketserver.BaseRequestHandler):
def handle(self):
data, server = self.request
server.sendto(data.upper(), self.client_address)
server = socketserver.ThreadingUDPServer(('127.0.0.1', 9999), MyRequestHanlder)
server.serve_forever()
udp服务端
from socket import *
client = socket(AF_INET,SOCK_DGRAM)
while True:
msg = input(">>>: ").strip()
client.sendto(msg.encode('utf-8'),('127.0.0.1',9999))
res,server_addr = client.recvfrom(1024)
print(res.decode('utf-8'))
基于udp的socketserver我们自己定义的类中的
- self.request是一个元组(第一个元素是客户端发来的数据,第二部分是服务端的udp套接字对象),如(b'adsf', )
- self.client_address即客户端地址
标签:socket,socketserver,实现,self,server,并发,client,data 来源: https://www.cnblogs.com/shof/p/14298626.html