Building a Simple Chat Application in Python using HTTP Server
Building a Simple Chat Application in Python using HTTP Server
In this article, we'll explore how to create a basic chat application using Python's built-in http.server
module. This application will allow users to join with a username, see connected users, send messages, and view received messages in real-time.
Introduction
Communication is a fundamental aspect of human interaction, and building a chat application is a great way to understand various networking concepts and improve your Python skills. In this tutorial, we'll walk through the process of creating a simple chat application using Python.
Prerequisites
To follow along, you'll need:
- Basic knowledge of Python.
- Familiarity with HTTP protocol.
Setting up the Environment
First, let's import the required libraries:
import socket
from http.server import BaseHTTPRequestHandler, HTTPServer
import webbrowser
import urllib.parse
We'll be using Python's built-in socket
and http.server
modules for handling connections and HTTP requests, respectively. The webbrowser
module will be used to open the chat interface in the default web browser.
Function to Get IP Address
We need a function to get the IP address of the machine:
def get_ip_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('8.8.8.8', 80))
ip_address = s.getsockname()[0]
finally:
s.close()
return ip_address
This function creates a UDP socket, connects to Google's DNS server (8.8.8.8), retrieves the socket name, and returns the IP address.
HTTP Request Handler Class
We define a class RequestHandler
to handle HTTP requests:
class RequestHandler(BaseHTTPRequestHandler):
connected_users = [] # List to store connected users
messages = [] # List to store messages
def do_GET(self):
# Handle GET requests
if self.path == '/':
# Serve HTML page for chat interface
# (HTML code provided in the code)
elif self.path == '/messages':
# Serve messages in HTML format
# (code provided)
elif self.path == '/users':
# Serve connected users in HTML format
# (code provided)
else:
# Handle 404 Not Found
self.send_error(404)
def do_POST(self):
# Handle POST requests
# (code provided)
The do_GET
method serves different requests based on the URL path. If the path is '/'
, it serves the HTML page for the chat interface. If the path is '/messages'
, it serves the messages in HTML format. If the path is '/users'
, it serves the connected users in HTML format. Otherwise, it returns a 404 Not Found error.
Function to Start the Server
Now, we define a function to start the HTTP server:
def start_server(port):
server_address = ('', port)
httpd = HTTPServer(server_address, RequestHandler)
print("Server started at {}:{}".format(get_ip_address(), port))
httpd.serve_forever()
This function creates an HTTP server on the specified port, using the RequestHandler
class to handle requests. It prints the server's IP address and port and starts serving requests indefinitely.
Generating the URL
We need a function to generate the URL:
def generate_url(port):
ip_address = get_ip_address()
return f"http://{ip_address}:{port}"
This function generates a URL with the server's IP address and port.
Main Function
Finally, we have the main function to orchestrate everything:
def main():
port = 8000 # Change this port number if needed
url = generate_url(port)
print("Share this URL with your friend to connect: ", url)
webbrowser.open(url) # Open the URL in the default web browser
start_server(port)
if __name__ == "__main__":
main()
The main
function sets the port number, generates the URL, prints it, opens it in the default web browser, and starts the server.
Conclusion
In this article, we learned how to create a simple chat application using Python's http.server
module. This application allows users to join, send messages, and view received messages in real-time. You can further enhance this application by adding features like private messaging, message history, or user authentication. Explore, experiment, and have fun coding!
Feel free to experiment with the code and customize it to fit your needs. Happy coding!