Implementing the UDP client

To begin implementing the client, we will need to declare the IP address that we will be trying to send our UDP messages to, as well as the port number. This port number is arbitrary, but you must ensure you aren't using a socket that has already been taken:

UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT = 6789
message = "Hello, Server"

Now, it's time to create the socket through which we will be sending our UDP message to the server: clientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM).

Once we've constructed our new socket, it's time to write the code that will send our UDP message: clientSocket.sendto(Message, (UDP_IP_ADDRESS, UDP_PORT)).

You can find the following code in the udp_client.py file inside the udp folder:

#!/usr/bin/env python3

import socket

UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT = 12345
buffer=4096

address = (UDP_IP_ADDRESS ,UDP_PORT)
socket_client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

while True:
message = input('Enter your message > ')
if message=="exit":
break
socket_client.sendto(message.encode(),address)
response,addr = socket_client.recvfrom(buffer)
print("Server response => %s" % response)

socket_client.close()

In the preceding code snippet, the UDP client sends a single line of text, Hello UDP server, and receives the response from the server. The following screenshot shows the request that's sent from the client to the server:

After inspecting the UDP client and server packets, we can easily see that UDP is much simpler than TCP. It's often termed as a connectionless protocol as there is no acknowledgment or error-checking involved.

The following screenshot shows the server's response, which was sent to the client:

In this section, we introduced the UDP and TCP protocols and the implementation of applications with the socket module, analyzing use cases such as creating a TCP client/server, and UDP client and server applications. We also reviewed how to inspect the client and server communication for TCP and UDP protocols with Wireshark.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset