Creating a random chat application like Omegle using Python sockets is a fun project. Below is a simplified version of such an application. This example demonstrates how two users can be randomly connected to chat with each other. Note that for a full-fledged application, you would need additional features such as handling multiple connections, user interface, and error handling.
Here's a basic example of a server and client code:
Server Code (server.py)
import socket
import threading
# List to keep track of connected clients
clients = []
def handle_client(client_socket):
# Add the client to the list of clients
clients.append(client_socket)
while True:
try:
message = client_socket.recv(1024)
if not message:
break
# Relay the message to all other clients
for client in clients:
if client != client_socket:
client.send(message)
except:
clients.remove(client_socket)
client_socket.close()
break
def start_server():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', 9999))
server.listen(5)
print("*Server started, waiting for connections...*")
while True:
client_socket, addr = server.accept()
print(f"*Connection established with {addr}*")
client_handler = threading.Thread(target=handle_client, args=(client_socket,))
client_handler.start()
if __name__ == "__main__":
start_server()
Client Code (client.py)
import socket
import threading
def receive_messages(client_socket):
while True:
try:
message = client_socket.recv(1024).decode('utf-8')
print(f"New message: {message}")
except:
print("*Connection closed by the server*")
client_socket.close()
break
def start_client():
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 9999))
print("*Connected to the chat server*")
recv_thread = threading.Thread(target=receive_messages, args=(client,))
recv_thread.start()
while True:
message = input()
if message.lower() == "exit":
break
client.send(message.encode('utf-8'))
client.close()
if __name__ == "__main__":
start_client()
Instructions
-
Run the Server:
- Save the server code in a file called
server.py.
- Run the server script using Python:
python server.py.
-
Run the Clients:
- Save the client code in a file called
client.py.
- Start the client script using Python:
python client.py.
- You can run multiple instances of the client in separate terminal windows to simulate a chat between users.
Note: This code is a basic example, and it's important to implement additional features like security, proper error handling, and connection management for a production-level application.