0% found this document useful (0 votes)
11 views2 pages

Python Chat Server with Client Handling

The document contains a Python script for a simple chat server that handles multiple clients using sockets and threading. It allows clients to connect, send messages, and broadcasts those messages to other clients while managing client connections and disconnections. The server runs on a specified host and port, and it can be shut down gracefully with a keyboard interrupt.

Uploaded by

Tanish Shukla
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Python Chat Server with Client Handling

The document contains a Python script for a simple chat server that handles multiple clients using sockets and threading. It allows clients to connect, send messages, and broadcasts those messages to other clients while managing client connections and disconnections. The server runs on a specified host and port, and it can be shut down gracefully with a keyboard interrupt.

Uploaded by

Tanish Shukla
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

import socket

import threading

clients = []
client_names = {}

def broadcast(message, sender_socket):


for client in clients:
if client != sender_socket:
try:
[Link]([Link]())
except:
[Link](client)

def handle_client(client_socket, address):


print(f"New connection from {address}")
client_socket.send("Enter your name: ".encode())
name = client_socket.recv(1024).decode().strip()
welcome = f"{name} joined the chat!"
print(welcome)
broadcast(welcome, client_socket)

[Link](client_socket)
client_names[client_socket] = name

try:
while True:
data = client_socket.recv(1024).decode()
if not data or [Link]() == 'exit':
break

message = f"{name}: {data}"


print(message)
broadcast(message, client_socket)
except:
pass
finally:
print(f"{name} disconnected.")
[Link](client_socket)
broadcast(f"{name} left the chat.", client_socket)
client_socket.close()
del client_names[client_socket]

def start_server(host='[Link]', port=65432):


server_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen()
print(f"Server running on {host}:{port}")

try:
while True:
client_socket, address = server_socket.accept()
[Link](target=handle_client, args=(client_socket, address),
daemon=True).start()
except KeyboardInterrupt:
print("\nServer shutting down.")
finally:
for client in clients:
[Link]()
server_socket.close()

if __name__ == '__main__':
start_server()

You might also like