网络编程(套接字)之UDP协议通信以及基于socketserver模块实现并发效果等相关内容-33
作者:互联网
1.基于udp协议的套接字通信
# server.py
# TCP VS UDP协议
# 1、可靠性
# tcp协议是可靠协议:
# 对方必须回复一个ack确认信息,才会将自己这端的数据从内存中删除
# udp协议不可靠:
# 发送一条消息就会立即删除,不管对方是否接收到
# 2、有无链接
# tcp有链接,udp无链接
# 3、传输数据的效率
# udp更高
# 4、粘包问题
# udp协议称之为数据报协议,每次发送都是一个完整的数据报,一个发送唯一对应一个接收
# 所以udp协议没有粘包问题
from socket import *
import time
server = socket(AF_INET, SOCK_DGRAM)
server.bind(('127.0.0.1', 8080))
while True:
data, client_addr = server.recvfrom(1024)
time.sleep(10)
server.sendto(data.upper(), client_addr)
# client.py
from socket import *
client = socket(AF_INET, SOCK_DGRAM)
while True:
msg = input('>>: ').strip()
client.sendto(msg.encode("utf-8"), ('127.0.0.1', 8080))
data, server_addr = client.recvfrom(1024)
print(data.decode('utf-8'))
2.基于socketserver模块实现并发tcp
# server.py
# from socket import *
#
#
# server=socket(AF_INET,SOCK_STREAM)
# server.bind(('127.0.0.1',8080))
# server.listen(5)
#
# while True:
# conn,addr=server.accept()
# print(addr)
#
# while True:
# try:
# data=conn.recv(1024)
# if len(data) == 0:break
# conn.send(data.upper())
# except Exception:
# break
#
# conn.close()
# 支持并发版本
import socketserver
class MyRequestHandler(socketserver.BaseRequestHandler):
def handle(self): # 处理通信
print(self.client_address)
while True:
try:
data = self.request.recv(1024) # self.request=>conn
if len(data) == 0: break
self.request.send(data.upper())
except Exception:
break
self.request.close()
if __name__ == '__main__':
s = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), MyRequestHandler, bind_and_activate=True)
s.serve_forever()
# client.py
from socket import *
client=socket(AF_INET,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'))
3.基于socketserver模块实现并发udp
# server.py
import socketserver
class MyRequestHandler(socketserver.BaseRequestHandler):
def handle(self): # 处理通信
data,server=self.request
server.sendto(data.upper(),self.client_address)
if __name__ == '__main__':
s = socketserver.ThreadingUDPServer(('127.0.0.1', 8080), MyRequestHandler, bind_and_activate=True)
s.serve_forever()
# client.py
from socket import *
client = socket(AF_INET, SOCK_DGRAM)
while True:
msg = input('>>: ').strip()
client.sendto(msg.encode("utf-8"), ('127.0.0.1', 8080))
data, server_addr = client.recvfrom(1024)
print(data.decode('utf-8'))
标签:UDP,socket,socketserver,True,server,client,接字,data 来源: https://www.cnblogs.com/usherwang/p/13525237.html