Build a Simple UDP Chat App in Python: Step‑by‑Step Tutorial
Learn how to create a basic UDP chat application in Python using the built‑in socket library, covering UDP protocol basics, environment setup, server and client code, execution steps, and tips for extending the program with multithreading or error handling.
Network programming is a powerful feature of Python, and building a UDP chat program is an excellent example to understand basic concepts. This tutorial uses Python's socket library to create a simple UDP chat allowing two users on the same network to exchange messages.
Introduction to UDP Protocol
UDP (User Datagram Protocol) is a simple connectionless transport‑layer protocol. Unlike TCP, it does not guarantee order or reliability, making it suitable for fast transmission scenarios such as video streaming or online games. Its lightweight nature also makes it ideal for a simple chat program, allowing us to focus on program logic rather than complex data transmission.
Environment Setup
Before starting, ensure Python 3.x is installed. No external libraries are required because the socket library is part of the Python standard library.
Creating the UDP Server
First, we create a UDP server to receive and forward messages.
import socket
def udp_server(host='127.0.0.1', port=12345):
# Create UDP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind socket to address and port
server_socket.bind((host, port))
print(f"UDP server up and listening at {host}:{port}")
try:
while True:
# Receive client message
message, client_address = server_socket.recvfrom(1024)
print(f"Message from {client_address}: {message.decode()}")
# Send response message
server_socket.sendto(b'Got your message!', client_address)
except KeyboardInterrupt:
server_socket.close()
print("
Server shutdown.")
if __name__ == "__main__":
udp_server()This code starts a UDP server listening on port 12345 (or any free port). It prints received messages and sends a confirmation back to the client.
Creating the UDP Client
Next, we create client code that sends messages to the UDP server and receives its response.
import socket
def udp_client(server_host='127.0.0.1', server_port=12345):
# Create UDP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
while True:
# Input message to send
message = input("Enter message to send: ")
if message == "exit":
break
# Send message to server
client_socket.sendto(message.encode(), (server_host, server_port))
# Receive server response
response, _ = client_socket.recvfrom(1024)
print(f"Server response: {response.decode()}")
finally:
client_socket.close()
print("Client shutdown.")
if __name__ == "__main__":
udp_client()The client prompts the user for input, encodes each message to bytes, sends it to the server, waits for the server's response, and prints it.
Running the Chat Program
To run the program, start the server in one terminal: python udp_server.py Then start the client in another terminal: python udp_client.py You can now type messages in the client window and see the server's responses. The server and client can run on different machines as long as they are on the same network.
Conclusion
Congratulations, you now have a working UDP chat program. Although simple, it covers fundamental network programming concepts and provides a foundation for exploring more complex network applications, such as adding multithreading for multiple clients or implementing error handling for network exceptions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
