python UDP CS demo
2024-08-23 15:55:07
UDP Communication
See also SoapOverUdp, TcpCommunication
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
最新文章
- prince2 证书有用吗
- Oracle基础语法
- 转: KindEditor 图片空间文件增加删除文件、文件夹功能(ASP语言环境)
- vs 2010 中类文文件模板的修改
- bcd 8421码
- 第一个demo
- 学习KMP算法
- Opacity多浏览器透明度兼容处理(转)
- JavaScript与FileSystemObject
- linux配置yum源
- .net DataTable 取值辅助类
- lucene 索引查看工具
- jsp页面遍历List<;Array>;
- Python高阶函数之 - 装饰器
- Redis常用数据类型和事物以及并发
- AI阅粒app
- VUE错误码Attribute &#39;:sizeOpts&#39; must be hyphenated
- docker 10 docker的镜像原理
- DAY14 函数(三)
- 阿里云配置ssl证书服务遇到的几个问题和解决方法
热门文章
- 第四篇: Ansible 常用模块使用
- 【Mac系统】之破解Navicat Premium for Mac(中文版)
- ios json结构
- python语言特性-------python2.7教程学习【廖雪峰版】(一)
- github 答题
- python 之前函数补充(__del__, item系列, __hash__, __eq__) , 以及模块初体验
- windowsphone8.1学习笔记之Toast通知
- OC常用函数及变量
- Redis 配置和使用
- threading.local的作用?