Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

COMPUTER NETWORKS

Server side:
import socket

import threading

def handle_client(client_socket, client_address):

print(f"Accepted connection from {client_address}")

while True:

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

if not data:

break

print(f"Received message from {client_address}: {data}")

for c in clients:

if c != client_socket:

c.sendall(data.encode('utf-8'))

clients.remove(client_socket)

client_socket.close()

print(f"Connection from {client_address} closed.")

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

host = '127.0.0.1'

port = 5555

server_socket.bind((host, port))

server_socket.listen(5)

print(f"Server listening on {host}:{port}")

clients = []

while True:

client_socket, client_address = server_socket.accept()

clients.append(client_socket)

client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))

client_thread.start()
CLIENT SIDE:
import socket

import threading

def receive_messages(sock):

while True:

try:

data = sock.recv(1024).decode('utf-8')

print(data)

except ConnectionAbortedError:

break

except:

print("An error occurred!")

sock.close()

break

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

host = '127.0.0.1'

port = 5555

client_socket.connect((host, port))

print("Connected to the server.")

receive_thread = threading.Thread(target=receive_messages, args=(client_socket,))

receive_thread.start()

while True:

message = input()

client_socket.sendall(message.encode('utf-8'))

You might also like