Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Client code: https://pastebin.com/Qvr47KF2
- #Server
- import socket
- import threading
- # Server configuration
- HOST = '127.0.0.1' # Accept connections from any IP
- PORT = 12347
- clients = []
- # Function to broadcast messages to all connected clients
- def broadcast_message(client_socket, message):
- for client in clients:
- if client != client_socket:
- try:
- client.send(message)
- except:
- client.close()
- remove_client(client)
- # Function to handle client connections
- def handle_client(client_socket):
- while True:
- try:
- message = client_socket.recv(1024)
- if message:
- #print(message.decode('utf-8'))
- broadcast_message(client_socket, message)
- else:
- remove_client(client_socket)
- except:
- continue
- # Function to remove a client from the list
- def remove_client(client_socket):
- if client_socket in clients:
- clients.remove(client_socket)
- client_socket.close()
- # Main server code
- server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- server.bind((HOST, PORT))
- server.listen(5)
- print("Chat server is running on port " + str(PORT))
- while True:
- client_socket, client_addr = server.accept()
- clients.append(client_socket)
- print("Client connected from " + str(client_addr))
- client_thread = threading.Thread(target=handle_client, args=(client_socket,))
- client_thread.start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement