手机
当前位置:查字典教程网 >脚本专栏 >python >python实现udp数据报传输的方法
python实现udp数据报传输的方法
摘要:本文实例讲述了Python实现UDP数据报传输的方法,非常具有实用价值。分享给大家供大家参考。具体方法分析如下:服务端代码:importso...

本文实例讲述了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实现udp数据报传输的方法】相关文章:

Python中使用中文的方法

python实现进程间通信简单实例

python二叉树遍历的实现方法

python处理文本文件实现生成指定格式文件的方法

python线程池的实现实例

python实现的一个p2p文件传输实例

python实现跨文件全局变量的方法

python去掉字符串中重复字符的方法

Python实现端口复用实例代码

python创建只读属性对象的方法(ReadOnlyObject)

精品推荐
分类导航