Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Code

simple lan chat project
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Code

simple lan chat project
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Server.

py
import socket

import threading

# Function to handle client connections

def handle_client(client_socket, clients):

while True:

try:

# Receive message from the client

message = client_socket.recv(1024).decode('utf-8')

if message:

print(f"Received: {message}")

broadcast_message(message, client_socket, clients)

else:

remove_client(client_socket, clients)

break

except:

continue

# Function to broadcast message to all clients

def broadcast_message(message, client_socket,clients):

for client in clients:

if client != client_socket:

try:

client.send(message.encode('utf-8'))

except:

remove_client(client, clients)
# Function to remove disconnected client

def remove_client(client_socket, clients):

if client_socket in clients:

clients.remove(client_socket)

client_socket.close()

# Main function to run the server

def start_server():

server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

server.bind(('0.0.0.0', 5555))

server.listen(5)

print("Server started. Waiting for connections...")

clients = []

while True:

client_socket, client_address = server.accept()

print(f"Connection established with {client_address}")

clients.append(client_socket)

threading.Thread(target=handle_client,args=(client_socket,
clients)).start()

if __name__ == "__main__":

start_server()

Client.py
import socket

import threading

# Function to receive messages from the server

def receive_messages(client_socket):

while True:

try:

message = client_socket.recv(1024).decode('utf-8')

if message:

print(f"\n{message}")

else:

break

except:

break

# Main function for client

def start_client():

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_ip = input("Enter server IP address: ")

client.connect((server_ip, 5555))

print("Connected to the server!")

threading.Thread(target=receive_messages, args=(client,)).start()

while True:

message = input()

client.send(message.encode('utf-8'))

if __name__ == "__main__":
start_client()

You might also like