Writing a UDP Client Program
Let's now write a client to go with the server we wrote.
The Server
Here’s the server code that we have so far for reference.
Press + to interact
import socketMAX_SIZE_BYTES = 65535 # Mazimum size of a UDP datagram# Setting up a sockets = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)port = 3000hostname = '127.0.0.1's.bind((hostname, port))print('Listening at {}'.format(s.getsockname()))while True:data, address = s.recvfrom(MAX_SIZE_BYTES)message = data.decode('ascii')upperCaseMessage = message.upper()print('The client at {} says {!r}'.format(clientAddress, message))data = upperCaseMessage.encode('ascii')s.sendto(data, clientAddress)
Creating a Client Socket
Instead of explicitly binding the socket to a given port and IP as we did previously, we can let the OS take care of it. Remember ephemeral ports? Yes, the OS will bind the socket to a port dynamically. So all we really need is to create a UDP socket (line 3).
Press + to interact
import sockets = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
In ...
Access this course and 1400+ top-rated courses and projects.