Building a chat application using Python sockets is a great way to understand networking concepts and socket programming. In this tutorial, we will create a simple chat app using Python’s built-in socket module.
What is Socket Programming?
Sockets allow communication between two nodes on a network. A server listens for incoming connections, while clients connect to the server to exchange messages.
Setting Up the Server
First, let’s create the server-side script that listens for client connections and facilitates communication.
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('0.0.0.0', 12345))
server_socket.listen(5)
print("Server started. Waiting for connections...")
client_socket, addr = server_socket.accept()
print(f"Connection established with {addr}")
while True:
message = client_socket.recv(1024).decode()
if message.lower() == 'exit':
break
print("Client:", message)
response = input("You: ")
client_socket.send(response.encode())
client_socket.close()
server_socket.close()
Creating the Client
Now, let’s write the client-side script that connects to the server.
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('127.0.0.1', 12345))
print("Connected to server.")
while True:
message = input("You: ")
client_socket.send(message.encode())
if message.lower() == 'exit':
break
response = client_socket.recv(1024).decode()
print("Server:", response)
client_socket.close()
Running the Chat Application
Follow these steps to run the chat app:
- Run the server script first:
python server.py - Run the client script in a separate terminal or another machine:
python client.py - Start chatting! Type messages and press enter to send.
- Type
exitto close the connection.
Conclusion
Congratulations! You’ve built a simple chat application using Python sockets. You can expand it by adding encryption, a GUI, or multi-client support.