UDP is widely used in network applications that require mutual data transmission. For example, QQ uses the UDP protocol. In the case of poor network quality, packet loss is very serious when UDP is used, but UDP occupies less resources and processes fast. UDP is still a commonly used protocol for data transmission.
The following is implemented using pythonUDP server code:
Copy codeThe Code is as follows:
#! /Usr/bin/env python
Import socket
Address = ('1970. 0.0.1 ', 127)
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:
Copy codeThe Code is as follows:
#! /Usr/bin/env python
Import socket
Addr = ('1970. 0.0.1 ', 127)
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:
Client:
UDP applications
In the LAN, If you want all computers in the LAN to send data, you can use broadcast, broadcast cannot use TCP, you can use UDP, after the recipient receives the broadcast data, if a process is listening on this port, it will receive data. If no process is listening, data packets will be discarded.
Broadcast Sender:
Copy codeThe 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 t KeyboardInterrupt:
Raise
Broadcast receiver:
Copy codeThe Code is as follows:
#! /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. The sending end displays the following results:
Copy codeThe Code is as follows:
Got data from ('<address>', <port number>)
Hello fromclient
The acceptor displays the following results:
Copy codeThe Code is as follows: ('broading', (<IP address>, 10000 ))