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,如需转载请自行联系原作者


相关文章
|
2月前
|
网络协议 Python
在Python中进行UDP(User Datagram Protocol)网络编程
在Python中进行UDP(User Datagram Protocol)网络编程
30 3
|
5月前
|
Python
python实现发送邮件demo
python实现发送邮件demo
38 1
|
5月前
|
Python
150 python网络编程 - UDP广播
150 python网络编程 - UDP广播
25 0
|
5月前
|
Python
147 python网络编程 - UDP案例
147 python网络编程 - UDP案例
27 0
|
5月前
|
Python
145 python网络编程 - UDP绑定信息
145 python网络编程 - UDP绑定信息
33 0
|
12天前
|
Python
Python网络编程基础(Socket编程)UDP服务器编程
【4月更文挑战第8天】Python UDP服务器编程使用socket库创建UDP套接字,绑定到特定地址(如localhost:8000),通过`recvfrom`接收客户端数据报,显示数据长度、地址和内容。无连接的UDP协议使得服务器无法主动发送数据,通常需应用层实现请求-响应机制。当完成时,用`close`关闭套接字。
|
17天前
|
Python
Python 循环使用demo
【4月更文挑战第3天】在Python中,主要的循环结构有for和while。示例包括:使用for循环打印列表[1, 2, 3, 4, 5],以及使用while循环计算1到10的和。`for i in [1, 2, 3, 4, 5]: print(i)`,以及`while count <= 10: sum += count; count += 1; print(sum)`。
11 2
|
1月前
|
网络协议 Python
Python网络编程实现TCP和UDP连接
Python网络编程实现TCP和UDP连接
27 0
|
1月前
|
网络协议 网络性能优化 Python
python怎么实现tcp和udp连接
python怎么实现tcp和udp连接
16 0
|
2月前
|
网络协议 网络安全 开发者
掌握Python网络编程:从TCP到UDP
掌握Python网络编程:从TCP到UDP