标签:消息 情况下 address 并发 enc 版本 客户 udp协议 utf-8
# 服务端
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)
# 服务端
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'))
标签:消息 情况下 address 并发 enc 版本 客户 udp协议 utf-8
原文地址:https://www.cnblogs.com/DcentMan/p/11380547.html