This article mainly introduces the udp protocol Server and Client code instances implemented by python. For more information, see the following code:
Server:
The code is as follows:
#! /Usr/bin/env python
# UDP Echo Server-udpserver. py
Import socket, traceback
Host =''
Port = 54321
S = socket. socket (socket. AF_INET, socket. SOCK_DGRAM)
S. setsockopt (socket. SOL_SOCKET, socket. SO_REUSEADDR, 1)
S. bind (host, port ))
While 1:
Try:
Message, address = s. recvfrom (8192)
Print "Got data from", address, ":", message
S. sendto (message, address)
Except t (KeyboardInterrupt, SystemExit ):
Raise
Except t:
Traceback. print_exc ()
Client:
The code is as follows:
1 #! /Usr/bin/env python
# UDP Client-udpclient. py
Import socket, sys
Host = sys. argv [1]
Textport = sys. argv [2]
S = socket. socket (socket. AF_INET, socket. SOCK_DGRAM)
Try:
Port = int (textport)
Failed T ValueError:
Port = socket. getservbyname (textport, 'udp ')
S. connect (host, port ))
While 1:
Print "Enter data to transmit :"
Data = sys. stdin. readline (). strip ()
S. sendall (data)
Print "Looking for replies; press Ctrl-C or Ctrl-Break to stop ."
Buf = s. recv (2048)
If not len (buf ):
Break
Print "Server replies :",
Sys. stdout. write (buf)
Print "\ n"