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

最新文章

  1. prince2 证书有用吗
  2. Oracle基础语法
  3. 转: KindEditor 图片空间文件增加删除文件、文件夹功能(ASP语言环境)
  4. vs 2010 中类文文件模板的修改
  5. bcd 8421码
  6. 第一个demo
  7. 学习KMP算法
  8. Opacity多浏览器透明度兼容处理(转)
  9. JavaScript与FileSystemObject
  10. linux配置yum源
  11. .net DataTable 取值辅助类
  12. lucene 索引查看工具
  13. jsp页面遍历List<Array>
  14. Python高阶函数之 - 装饰器
  15. Redis常用数据类型和事物以及并发
  16. AI阅粒app
  17. VUE错误码Attribute ':sizeOpts' must be hyphenated
  18. docker 10 docker的镜像原理
  19. DAY14 函数(三)
  20. 阿里云配置ssl证书服务遇到的几个问题和解决方法

热门文章

  1. 第四篇: Ansible 常用模块使用
  2. 【Mac系统】之破解Navicat Premium for Mac(中文版)
  3. ios json结构
  4. python语言特性-------python2.7教程学习【廖雪峰版】(一)
  5. github 答题
  6. python 之前函数补充(__del__, item系列, __hash__, __eq__) , 以及模块初体验
  7. windowsphone8.1学习笔记之Toast通知
  8. OC常用函数及变量
  9. Redis 配置和使用
  10. threading.local的作用?