Created
August 16, 2025 01:15
-
-
Save SiddharthShyniben/a8ace514830ed4083443f00cff890894 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import threading | |
import argparse | |
HOST = "0.0.0.0" # Server binds here (0.0.0.0 = all interfaces) | |
PORT = 5000 # Default port | |
def handle_client(conn, addr, clients): | |
"""Handle incoming messages from a single client and broadcast to others.""" | |
print(f"[+] Connected: {addr}") | |
with conn: | |
while True: | |
try: | |
data = conn.recv(1024) | |
if not data: | |
break | |
msg = data.decode("utf-8").strip() | |
print(f"[{addr}] {msg}") | |
# Broadcast to all other clients | |
for c in clients: | |
if c is not conn: | |
try: | |
c.sendall(f"{addr}: {msg}\n".encode("utf-8")) | |
except: | |
pass | |
except ConnectionResetError: | |
break | |
print(f"[-] Disconnected: {addr}") | |
clients.remove(conn) | |
def run_server(): | |
"""Start the server and accept clients.""" | |
clients = [] | |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
s.bind((HOST, PORT)) | |
s.listen() | |
print(f"[*] Server listening on {HOST}:{PORT}") | |
while True: | |
conn, addr = s.accept() | |
clients.append(conn) | |
threading.Thread( | |
target=handle_client, args=(conn, addr, clients), daemon=True | |
).start() | |
def listen_for_messages(sock): | |
"""Listen for messages from the server and print them.""" | |
while True: | |
data = sock.recv(1024) | |
if not data: | |
break | |
print(data.decode("utf-8").strip()) | |
def run_client(server_ip): | |
"""Connect to a server and send/receive messages.""" | |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
s.connect((server_ip, PORT)) | |
print(f"[*] Connected to server at {server_ip}:{PORT}") | |
threading.Thread(target=listen_for_messages, args=(s,), daemon=True).start() | |
while True: | |
msg = input("> ") | |
if msg.strip().lower() in {"quit", "exit"}: | |
break | |
s.sendall((msg + "\n").encode("utf-8")) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description="Client/Server Engine") | |
parser.add_argument("mode", choices=["server", "client"], help="Run as server or client") | |
parser.add_argument("--host", help="Server IP (for client mode)", default="127.0.0.1") | |
args = parser.parse_args() | |
if args.mode == "server": | |
run_server() | |
else: | |
run_client(args.host) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment