python UDP CS demo
Python Demo UDP cs
2023-09-14 09:11:56 时间
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
相关文章
- 浙江新增python编程_9月起,浙江省八年级新增Python编程课,未来编程是处理大数据的手段…「建议收藏」
- python fileinput_Python之fileinput模块学习「建议收藏」
- 【说站】python中Git分支操作
- 使用 OpenCV 和 Python 模糊和匿名化人脸
- python udp编程_Python核心编程
- python抛出异常和捕获异常_Python异常
- python上的表白代码_用Python实现表白代码
- python 微信自动回复机器人
- python deepcopy函数_Python deepcopy
- 【分享】Python 多缺口滑块验证demo
- 太好玩了,我用 Python 做了一个 ChatGPT 机器人
- python-Python与SQLite数据库-SQLite数据库的基本知识(二)
- python-Python与SQLite数据库-使用Python执行SQLite查询(二)
- python-Python与PostgreSQL数据库-使用Python执行PostgreSQL查询(一)
- python压缩和读取.tar.bz2格式的压缩包详解编程语言
- python模块之psutil详解编程语言
- python-模块-tkinter详解编程语言
- Python爬取MySQL数据,助力数据分析(python读取mysql数据)
- Redis锁实现Demo简洁而又安全(redis锁写demo)
- Python变量类型及命名规则介绍
- python插入排序算法的实现代码
- python翻译软件实现代码(使用googleapi完成)
- Python中多线程及程序锁浅析