python udp数据报

每个语言都有自己的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),参考代码示例很容易能理解。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值