Python3 implements UDP server and client, and python3 implements udp
Use the socket module in Python to implement the UDP protocol. Here we write a simple server and client. In order to illustrate the UDP application in network programming, we will not write a graphical representation here. Simply open the UDP client and server on both computers.
UDP: User Datagram Protocol. It is a connectionless protocol. Using this Protocol does not require two applications to establish a connection first. UDP does not provide error recovery and data retransmission. Therefore, this protocol has poor data transmission security.
Client
Python3 can only send and receive binary data and needs explicit Transcoding
From socket import * host = '2017. 168.48.128 '# This is the ipport = 13141 of the client's computer # The interface is greater than 10000 to avoid conflict with the bufsize = 1024 # define the buffer size addr = (host, port) # original udpClient = socket (AF_INET, SOCK_DGRAM) # create a client while True: data = input ('>>>') if not data: break data = data. encode (encoding = "UTF-8") udpClient. sendto (data, addr) # send data, addr = udpClient. recvfrom (bufsize) # receive data and return address print (data. decode (encoding = "UTF-8"), 'from', addr) udpClient. close ()
Server
Explicit transcoding is also required
From socket import * from time import ctimehost = ''# Listen to all ipports = 13141 # interface must be consistent bufsize = 1024 addr = (host, port) udpServer = socket (AF_INET, SOCK_DGRAM) udpServer. bind (addr) # Start listening while True: print ('Waiting for connection... ') data, addr = udpServer. recvfrom (bufsize) # receive data and return address # process data = data. decode (encoding = 'utf-8 '). upper () data = "at % s: % s" % (ctime (), data) udpServer. sendto (data. encode (encoding = 'utf-8'), addr) # send data print ('... recevied from and return to: ', addr) udpServer. close ()
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.