Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
udp does not require 3-way handshake and four waving, without establishing a connection in advance, send the data directly on the line.
end server
#-*- coding: utf-8 -*-
import socket
import binascii
BUFSIZE = 1500
ip_port = ('0.0.0.0', 3480) #host 端口
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # udp协议
server.bind(ip_port)
while True:
try:
data,client_addr = server.recvfrom(BUFSIZE)
except Exception as e:
print('client_addr error is : %s' % e)
print('server收到的数据', binascii.b2a_hex(data).decode()) #打印接受到的数据
#server.sendto(data.upper(),client_addr)
server.close()
client end
import socket
BUFSIZE = 1024
client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while True:
msg = input(">> ").strip()
ip_port = ('127.0.0.1', 9999)
client.sendto(msg.encode('utf-8'),ip_port)
data,server_addr = client.recvfrom(BUFSIZE)
print('客户端recvfrom ',data,server_addr)
client.close()