每个语言都有自己的udp
数据报传输和接收方式,但是python
的代码很短,类似如下
# sender.py
from socket import * # import the module for socket
sender = socket(AF_INET,SOCK_DGRAM) # the args stand for udp
addr = ('127.0.0.1',10002) # send to this address
data = 'Hello world!'.encode() # encoding is required
try:
sender.sendto(data,addr) # send the data to addr
except:
print('An error occurs while sending data')
# server.py
from socket import * # import the module for socket
server = socket(AF_INET,SOCK_DGRAM) # the args stand for udp
addr = ('',10002) # '' means any address/
# use an unempty str to specify
# 10002 means binding port
server.bind(addr) # start to listen
data,addr = server.recvfrom(1024) # 1024 means get at most 1024B
# return a tuple
# first is data sent
# second is a tuple of address
print('Receive data from {} through port 10002.'.format(addr[0]))
print('It is sent from source port {}.'.format(addr[1]))
print('='*25+'Data Start'+'='*25)
print(data.decode())
print('='*26+'Data End'+'='*26)
在python
中进行udp
传输非常简单,发送使用socket.sendto(data,addr)
,接收使用socket.recvfrom(length)
,参考代码示例很容易能理解。