UDP is widely used in network applications that need to transmit data to each other, such as the UDP protocol used by QQ. In the case of poor network quality, packet loss is very serious when using UDP protocol, but UDP consumes less resources, processing speed is fast, UDP is still the commonly used protocol for transmitting data.
Here is the code for implementing a UDP server with Python:
The code is as follows:
#!/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 ()
Code for the UDP client:
The code is as follows:
#!/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 the two programs displays the following results:
Server-side:
Client:
Application of UDP
In the local area network, if you want to send data to all the computers in the LAN, you can use the broadcast, broadcast cannot be implemented with TCP, can be implemented with UDP, the receiving party receives broadcast data, if there is a process listening to this port, it will receive data, if there is no process to listen, the packet will be discarded.
The sending party of the broadcast:
The code is as follows:
#!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 Broadcast:
The code is as follows:
#!/usr/bin/env python
Import Socket,sys
Addr= (' , 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
To run the broadcast program, the sending side displays the following results:
The code is as follows:
Got data from (" <地址> , <端口号> )
Hello Fromclient
The following results are displayed on the receiving side:
The code is as follows:
(' Broading ', ( , 10000))