UDP通信
Posted dcentman
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UDP通信相关的知识,希望对你有一定的参考价值。
UDP协议通信
一、特点
- 数据报协议(自带报头)
- 没有双向通道,通信类似于发短信,而TCP协议类似于打电话
二、简易版
# 服务端
import socket
server = socket.socket(type=socket.SOCK_DGRAM) # UDP协议
server.bind(('127.0.0.1',8080))
# UDP不需要设置半连接池 它也没有半连接池的概念
# 因为没有双向通道 不需要accept 直接就是通信循环
while True:
data, addr = server.recvfrom(1024)
print('数据:',data) # 客户端发来的消息
print('地址:',addr) # 客户端的地址
server.sendto(data.upper(),addr)
# 客户端
import socket
client = socket.socket(type=socket.SOCK_DGRAM)
# 不需要建立连接 直接进入通信循环
server_address = ('127.0.0.1',8080)
while True:
client.sendto(b'hello',server_address)
data, addr = client.recvfrom(1024)
print('服务端发来的数据',data)
print('服务端的地址',addr)
三、UDP与TCP之间的区别
- UDP协议客户端允许发空
- UDP协议不会粘包
- UDP协议服务端不存在的情况下,客户端照样不会报错
- UDP协议支持并发
四、UDP实现简易版本QQ
# 服务端
import socket
server = socket.socket(type=socket.SOCK_DGRAM)
server.bind(('127.0.0.1',8080))
while True:
data, addr = server.recvfrom(1024)
print(data.decode('utf-8'))
msg = input('>>>:')
server.sendto(msg.encode('utf-8'),addr)
# 客户端1
import socket
client = socket.socket(type=socket.SOCK_DGRAM)
server_address = ('127.0.0.1',8080)
while True:
msg = input('>>>:')
msg = '来自客户端1的消息:%s'%msg
client.sendto(msg.encode('utf-8'),server_address)
data, server_addr = client.recvfrom(1024)
print(data.decode('utf-8'))
# 客户端2
import socket
client = socket.socket(type=socket.SOCK_DGRAM)
server_address = ('127.0.0.1',8080)
while True:
msg = input('>>>:')
msg = '来自客户端2的消息:%s'%msg
client.sendto(msg.encode('utf-8'),server_address)
data, server_addr = client.recvfrom(1024)
print(data.decode('utf-8'))
# 客户端3
import socket
client = socket.socket(type=socket.SOCK_DGRAM)
server_address = ('127.0.0.1',8080)
while True:
msg = input('>>>:')
msg = '来自客户端3的消息:%s'%msg
client.sendto(msg.encode('utf-8'),server_address)
data, server_addr = client.recvfrom(1024)
print(data.decode('utf-8'))
# 客户端4
import socket
client = socket.socket(type=socket.SOCK_DGRAM)
server_address = ('127.0.0.1',8080)
while True:
msg = input('>>>:')
msg = '来自客户端4的消息:%s'%msg
client.sendto(msg.encode('utf-8'),server_address)
data, server_addr = client.recvfrom(1024)
print(data.decode('utf-8'))
# 客户端5
import socket
client = socket.socket(type=socket.SOCK_DGRAM)
server_address = ('127.0.0.1',8080)
while True:
msg = input('>>>:')
msg = '来自客户端5的消息:%s'%msg
client.sendto(msg.encode('utf-8'),server_address)
data, server_addr = client.recvfrom(1024)
print(data.decode('utf-8'))
以上是关于UDP通信的主要内容,如果未能解决你的问题,请参考以下文章