python3 implements UDP protocol server and client


Using socket module in Python to implement the UDP protocol, write a simple server and client here. To illustrate the use of UDP in network programming, I will not write graphics here, but open the client and server of UDP respectively on two computers.

UDP: User Datagram Protocol, a connectionless protocol. Using this protocol does not require two applications to establish a connection first. The UDP protocol does not provide error recovery and cannot provide data retransmission, so the security of the transmitted data is poor.

The client

python3 can only send and receive binary data and requires explicit transcoding

from socket import *

host = '192.168.48.128' #  This is for the client computer ip
port = 13141 # Interface selection greater than 10000 To avoid conflict
bufsize = 1024 # Define buffer size

addr = (host,port) #  Tuples form
udpClient = socket(AF_INET,SOCK_DGRAM) # Create client

while True:
  data = input('>>> ')
  if not data:
    break
  data = data.encode(encoding="utf-8")
  udpClient.sendto(data,addr) #  To send data
  data,addr = udpClient.recvfrom(bufsize) # Receive data and return address
  print(data.decode(encoding="utf-8"),'from',addr)

udpClient.close()

The server

Explicit transcoding is also required

from socket import *
from time import ctime

host = '' # Listen for all ip
port = 13141 # Interface must be 1 to
bufsize = 1024
addr = (host,port)

udpServer = socket(AF_INET,SOCK_DGRAM)
udpServer.bind(addr) # To start listening to

while True:
 print('Waiting for connection...')
 data,addr = udpServer.recvfrom(bufsize) # Receive data and return address
 # Process the data
 data = data.decode(encoding='utf-8').upper()
 data = "at %s :%s"%(ctime(),data)
 udpServer.sendto(data.encode(encoding='utf-8'),addr)
 # To send data
 print('...recevied from and return to :',addr)

udpServer.close()