Advertisement
LEGEND2004

Server

Oct 21st, 2023 (edited)
1,126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. #Client code: https://pastebin.com/Qvr47KF2
  2.  
  3. #Server
  4. import socket
  5. import threading
  6.  
  7. # Server configuration
  8. HOST = '127.0.0.1'  # Accept connections from any IP
  9. PORT = 12347
  10. clients = []
  11.  
  12. # Function to broadcast messages to all connected clients
  13. def broadcast_message(client_socket, message):
  14.     for client in clients:
  15.         if client != client_socket:
  16.             try:
  17.                 client.send(message)
  18.             except:
  19.                 client.close()
  20.                 remove_client(client)
  21.  
  22. # Function to handle client connections
  23. def handle_client(client_socket):
  24.     while True:
  25.         try:
  26.             message = client_socket.recv(1024)
  27.             if message:
  28.                 #print(message.decode('utf-8'))
  29.                 broadcast_message(client_socket, message)
  30.             else:
  31.                 remove_client(client_socket)
  32.         except:
  33.             continue
  34.  
  35. # Function to remove a client from the list
  36. def remove_client(client_socket):
  37.     if client_socket in clients:
  38.         clients.remove(client_socket)
  39.         client_socket.close()
  40.  
  41. # Main server code
  42. server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  43. server.bind((HOST, PORT))
  44. server.listen(5)
  45.  
  46. print("Chat server is running on port " + str(PORT))
  47.  
  48. while True:
  49.     client_socket, client_addr = server.accept()
  50.     clients.append(client_socket)
  51.     print("Client connected from " + str(client_addr))
  52.     client_thread = threading.Thread(target=handle_client, args=(client_socket,))
  53.     client_thread.start()
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement