Guest User

Untitled

a guest
Nov 23rd, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  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.  
  6.  
  7. def accept_incoming_connections():
  8. """Sets up handling for incoming clients."""
  9. while True:
  10. client, client_address = SERVER.accept()
  11. print("%s:%s has connected." % client_address)
  12. client.send(bytes("Greetings from the cave! Now type your name and press enter!", "utf8"))
  13. addresses[client] = client_address
  14. Thread(target=handle_client, args=(client,)).start()
  15.  
  16.  
  17. def handle_client(client): # Takes client socket as argument.
  18. """Handles a single client connection."""
  19.  
  20. name = client.recv(BUFSIZ).decode("utf8")
  21. welcome = 'Welcome %s! If you ever want to quit, type {quit} to exit.' % name
  22. client.send(bytes(welcome, "utf8"))
  23. msg = "%s has joined the chat!" % name
  24. broadcast(bytes(msg, "utf8"))
  25. clients[client] = name
  26.  
  27. while True:
  28. msg = client.recv(BUFSIZ)
  29. if msg != bytes("{quit}", "utf8"):
  30. broadcast(msg, name+": ")
  31. else:
  32. client.send(bytes("{quit}", "utf8"))
  33. client.close()
  34. del clients[client]
  35. broadcast(bytes("%s has left the chat." % name, "utf8"))
  36. break
  37.  
  38.  
  39. def broadcast(msg, prefix=""): # prefix is for name identification.
  40. """Broadcasts a message to all the clients."""
  41.  
  42. for sock in clients:
  43. sock.send(bytes(prefix, "utf8")+msg)
  44.  
  45.  
  46. clients = {}
  47. addresses = {}
  48.  
  49. HOST = ''
  50. PORT = 33000
  51. BUFSIZ = 1024
  52. ADDR = (HOST, PORT)
  53.  
  54. SERVER = socket(AF_INET, SOCK_STREAM)
  55. SERVER.bind(ADDR)
  56.  
  57. if __name__ == "__main__":
  58. SERVER.listen(5)
  59. print("Waiting for connection...")
  60. ACCEPT_THREAD = Thread(target=accept_incoming_connections)
  61. ACCEPT_THREAD.start()
  62. ACCEPT_THREAD.join()
  63. SERVER.close()
Add Comment
Please, Sign In to add comment