You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.8 KiB

4 years ago
  1. #!/usr/bin/env python3
  2. """Server for multithreaded (asynchronous) chat application."""
  3. from socket import AF_INET, socket, SOCK_STREAM
  4. from threading import Thread
  5. def accept_incoming_connections():
  6. """Sets up handling for incoming clients."""
  7. while True:
  8. client, client_address = SERVER.accept()
  9. print("%s:%s has connected." % client_address)
  10. client.send(bytes("Willkommen zum Brieftaube Messenger! Schreibe deinen Namen rein und druecke Enter!", "utf8"))
  11. addresses[client] = client_address
  12. Thread(target=handle_client, args=(client,)).start()
  13. def handle_client(client): # Takes client socket as argument.
  14. """Handles a single client connection."""
  15. name = client.recv(BUFSIZ).decode("utf8")
  16. welcome = 'Welcome %s! If you ever want to quit, type {quit} to exit.' % name
  17. client.send(bytes(welcome, "utf8"))
  18. msg = "%s has joined the chat!" % name
  19. broadcast(bytes(msg, "utf8"))
  20. clients[client] = name
  21. while True:
  22. msg = client.recv(BUFSIZ)
  23. if msg != bytes("{quit}", "utf8"):
  24. broadcast(msg, name+": ")
  25. else:
  26. client.send(bytes("{quit}", "utf8"))
  27. client.close()
  28. del clients[client]
  29. broadcast(bytes("%s has left the chat." % name, "utf8"))
  30. break
  31. def broadcast(msg, prefix=""): # prefix is for name identification.
  32. """Broadcasts a message to all the clients."""
  33. for sock in clients:
  34. sock.send(bytes(prefix, "utf8")+msg)
  35. clients = {}
  36. addresses = {}
  37. HOST = 'localhost'
  38. PORT = 33000
  39. BUFSIZ = 1024
  40. ADDR = (HOST, PORT)
  41. SERVER = socket(AF_INET, SOCK_STREAM)
  42. SERVER.bind(ADDR)
  43. if __name__ == "__main__":
  44. SERVER.listen(5)
  45. print("Waiting for connection...")
  46. ACCEPT_THREAD = Thread(target=accept_incoming_connections)
  47. ACCEPT_THREAD.start()
  48. ACCEPT_THREAD.join()
  49. SERVER.close()