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 bad network quality, the packet loss is very serious when using UDP protocol, but the UDP occupies less resources and the processing speed is fast, UDP is still a common protocol for data transmission.
Here's the code to implement the UDP server in Python:
Copy Code code 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 ()
UDP Client code:
Copy Code code 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 these 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 computers in the LAN, you can use the broadcast, broadcast cannot be implemented with TCP, can be implemented with UDP, recipient received broadcast data, if there is a process listening to this port, will receive data, if no process listening, packets will be discarded.
Sender of Broadcast:
Copy Code code 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:
Copy Code code 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, and the sender will display the following results:
Copy Code code as follows:
Got data from (' < address > ',< port number >)
Hello Fromclient
The receiving end displays the following results:
Copy Code code as follows:
(' Broading ', (<ip address >,10000))