UDP instance of python network programming (including server side client side UDP broadcast example)
- 2020-04-02 13:36:22
- OfStack
UDP is widely used in network applications that need to transmit data to each other, such as QQ, which USES the UDP protocol. In the case of poor network quality, the phenomenon of packet loss is very serious when using UDP protocol, but UDP occupies less resources and has fast processing speed. UDP is still a frequently used protocol for data transmission.
The following is implemented in python
UDP server code:
#!/usr/bin/env python
import socket
address=('127.0.0.1',10000)
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(address)
while 1:
data,addr=s.recvfrom(2048)
if not data:
break
print "got data from",addr
print data
s.close()
UDP client code:
#!/usr/bin/env python
import socket
addr=('127.0.0.1',10000)
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while 1:
data=raw_input()
if not data:
break
s.sendto(data,addr)
s.close()
Running these two programs will display the following results:
Server-side:
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201404/2014425104027643.jpg? 2014325104042 ">
Client:
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201404/2014425104102924.jpg? 2014325104114 ">
The application of UDP
In the LAN, if you want to send data to all the computers in the LAN, you can use the broadcast. The broadcast cannot be implemented by TCP, but can be implemented by UDP. After the receiver receives the broadcast data, if there is a process listening on this port, it will receive the data.
Sender of the broadcast:
#!usr/bin/env python
import socket
host=''
port=10000
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
s.bind((host,port))
while 1:
try:
data,addr=s.recvfrom(1024)
print "got data from",addr
s.sendto("broadcasting",addr)
print data
except KeyboardInterrupt:
raise
Receiver of the broadcast:
#!/usr/bin/env python
import socket,sys
addr=('<broadcast>',10000)
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
s.sendto("hello from client",addr)
while 1:
data=s.recvfrom(1024)
if not data:
break
print data
Run the broadcast program, and the sender will display the following results:
got data from ( ' < address >',< The port number >)
hello fromclient
The receiver will display the following results:
( ' broading',(<IP address > . 10000))