开发者社区> 桃子红了呐> 正文

python UDP CS demo

简介:
+关注继续查看

UDP Communication

 

See also SoapOverUdpTcpCommunication

 

Sending

Here's simple code to post a note by UDP in Python:

 

Toggle line numbers
   1 import socket
   2 
   3 UDP_IP = "127.0.0.1"
   4 UDP_PORT = 5005
   5 MESSAGE = "Hello, World!"
   6 
   7 print "UDP target IP:", UDP_IP
   8 print "UDP target port:", UDP_PORT
   9 print "message:", MESSAGE
  10 
  11 sock = socket.socket(socket.AF_INET, # Internet
  12                      socket.SOCK_DGRAM) # UDP
  13 sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))

 

Receiving

Here's simple code to receive UDP messages in Python:

 

Toggle line numbers
   1 import socket
   2 
   3 UDP_IP = "127.0.0.1"
   4 UDP_PORT = 5005
   5 
   6 sock = socket.socket(socket.AF_INET, # Internet
   7                      socket.SOCK_DGRAM) # UDP
   8 sock.bind((UDP_IP, UDP_PORT))
   9 
  10 while True:
  11     data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
  12     print "received message:", data

 

Using UDP for e.g. File Transfers

If considering extending this example for e.g. file transfers, keep in mind that UDP is not reliable. So you'll have to handle packets getting lost and packets arriving out of order. In effect, to get something reliable you'll need to implement something similar to TCP on top of UDP, and you might want to consider using TCP instead.

That being said, sometimes you need to use UDP, e.g. for UDP hole punching. In that case, consider TFTP for python or UDT for python










本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/bonelee/p/6420218.html,如需转载请自行联系原作者


版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
基于Python的TCP和UDP数据流的带宽竞争分析(附完整代码)
基于Python的TCP和UDP数据流的带宽竞争分析(附完整代码)
34 0
socket库:Python实现UDP客户和服务器通信
socket库:Python实现UDP客户和服务器通信
84 0
python udp网络
搬运自本人csdn博客
52 0
Python编程:socket实现udp通讯
Python编程:socket实现udp通讯
43 0
Python 多任务1: 线程&多线程版UDP聊天器
Python 多任务1: 线程&多线程版UDP聊天器
78 0
Python 网络编程2:UDP-发送、接收数据
Python 网络编程2:UDP-发送、接收数据
285 0
python脚本基于UDP主机信息收集
python脚本基于UDP主机信息收集
52 0
Python网络编程之UDP
Python网络编程之UDP
114 0
python web开发 网络编程 TCP/IP UDP协议
python web开发 网络编程 TCP/IP UDP协议
133 0
Python 技术篇-socket套接字实现服务器客户端消息传递实例演示,UDP实现
Python 技术篇-socket套接字实现服务器客户端消息传递实例演示,UDP实现
96 0
文章
问答
文章排行榜
最热
最新
相关电子书
更多
给运维工程师的Python实战课
立即下载
Python 脚本速查手册
立即下载
ACE 区域技术发展峰会:Flink Python Table API入门及实践
立即下载