#导入 socket
import socket
#导入 random
import random
#输入‘server’为服务端,输入‘client’为客户端
a=input('server/client :')
#定义服务端
def server():
# 初始化
sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('127.0.0.1',9595))
print('Listening at',sock.getsockname())
while True:
# 接收数据包大小
data,address=sock.recvfrom(65535)
if random.random() < 0.5:
print("Pretening to drop packet from {}".format(address))
continue
text=data.decode('ascii')
print('The client at {} says {!r}'.format(address,text))
message='Your data was {} bytes long'.format(len(data))
sock.sendto(message.encode('ascii'),address)
#定义客户端
def client():
while True:
# 初始化
sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.connect(('127.0.0.1',9595))
print('Client socket name is {}'.format(sock.getsockname()))
delay=0.1
# text='This is another message'
# text是输入要发送的内容
text=input('@:')
data = text.encode('ascii')
while True:
sock.send(data)
print('Waiting up to {} seconds for a reply'.format(delay))
sock.settimeout(delay)
try:
data=sock.recv(65535)
except sock.timeout:
delay*=1.0
continue
if delay > 2.0:
raise RuntimeError('I think the server is down')
continue
else:
continue
print('The server says {!r}'.format(data.decode('ascii')))
if a == 'server':
server()
else:
client()
Python发送UDP数据包
于 2023-11-03 17:22:30 首次发布