python实现udp数据报传输的方法

yipeiwu_com6年前Python基础

本文实例讲述了Python实现UDP数据报传输的方法,非常具有实用价值。分享给大家供大家参考。具体方法分析如下:

服务端代码:

import socket 
port = 8081 
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 
#从给定的端口,从任何发送者,接收UDP数据报 
s.bind(("",port)) 
print 'waiting on port:',port 
while True: 
  data,addr = s.recvfrom(1024) 
  #接收一个数据报(最大到1024字节) 
  print 'reciveed:',data,"from",addr 

客户端代码:

import socket 
port = 8081 
host = "localhost" 
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 
s.sendto("hello world",(host,port)) 

结果:先运行服务端,然后运行客户端,
服务端打印出:

waiting on port: 8081
reciveed: hello world from ('127.0.0.1', 62644)

补充:
socket.sendto(string[, flags], address)

官方文档如下:

Send data to the socket. The socket should not be connected to a remote socket, since the destination socket is specified by address. The optional flags argument has the same meaning as for recv() above. Return the number of bytes sent. (The format of address depends on the address family — see above.)address参数在协议类型为socket.SOCK_DGRAM时,address的结构为一个元组,(host,port)的格式

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python函数any()和all()的用法及区别介绍

引子 平常的文本处理工作中,我经常会遇到这么一种情况:用python判断一个string是否包含一个list里的元素。 这时候使用python的内置函数any()会非常的简洁: fr...

python 设置xlabel,ylabel 坐标轴字体大小,字体类型

本文介绍了python 设置xlabel,ylabel 坐标轴字体大小,字体类型,分享给大家,具体如下: #--coding:utf-8-- import matplotlib.p...

python二分法查找算法实现方法【递归与非递归】

本文实例讲述了python二分法查找算法实现方法。分享给大家供大家参考,具体如下: 二分法查找 二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表...

Python使用random模块生成随机数操作实例详解

本文实例讲述了Python使用random模块生成随机数操作。分享给大家供大家参考,具体如下: 今天在用Python编写一个小程序时,要用到随机数,于是就在网上查了一下关于Python生...

Python Unittest自动化单元测试框架详解

Python Unittest自动化单元测试框架详解

本文实例为大家分享了Python Unittest自动化单元测试框架的具体代码,供大家参考,具体内容如下 1、python 测试框架(本文只涉及 PyUnit) 参考地址 2、环境准备...