UDP is a user datagram transmission protocol. It is located at the TCPIP transport layer and is a connectionless protocol, the packet sent by QQ cannot be sure whether it has completely reached the other end. UDP is widely used in network applications that need to transmit data to each other. For example, QQ uses UDP. 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:
The 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:
The 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:
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 t KeyboardInterrupt:
Raise
Broadcast receiver:
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
Run the broadcast program. The sending end displays the following results:
The Code is as follows:
Got data from (' <地址> ', <端口号> )
Hello fromclient
The acceptor displays the following results:
The Code is as follows:
('Broading ',( , 10000 ))