Posted By

grzyweasel on 01/06/11


Tagged

server chat


Versions (?)

Chat Server


 / Published in: Python
 

URL: http://rosettacode.org/wiki/Chat_server#Python

code by Stephen McDonald

  1. #!/usr/bin/env python
  2.  
  3. import socket
  4. import thread
  5. import time
  6.  
  7. HOST = ""
  8. PORT = 4004
  9.  
  10. def accept(conn):
  11. """
  12. Call the inner func in a thread so as not to block. Wait for a
  13. name to be entered from the given connection. Once a name is
  14. entered, set the connection to non-blocking and add the user to
  15. the users dict.
  16. """
  17. def threaded():
  18. while True:
  19. conn.send("Please enter your name: ")
  20. try:
  21. name = conn.recv(1024).strip()
  22. except socket.error:
  23. continue
  24. if name in users:
  25. conn.send("Name entered is already in use.\n")
  26. elif name:
  27. conn.setblocking(False)
  28. users[name] = conn
  29. broadcast(name, "+++ %s arrived +++" % name)
  30. break
  31. thread.start_new_thread(threaded, ())
  32.  
  33. def broadcast(name, message):
  34. """
  35. Send a message to all users from the given name.
  36. """
  37. print message
  38. for to_name, conn in users.items():
  39. if to_name != name:
  40. try:
  41. conn.send(message + "\n")
  42. except socket.error:
  43. pass
  44.  
  45. # Set up the server socket.
  46. server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  47. server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  48. server.setblocking(False)
  49. server.bind((HOST, PORT))
  50. server.listen(1)
  51. print "Listening on %s" % ("%s:%s" % server.getsockname())
  52.  
  53. # Main event loop.
  54. users = {}
  55. while True:
  56. try:
  57. # Accept new connections.
  58. while True:
  59. try:
  60. conn, addr = server.accept()
  61. except socket.error:
  62. break
  63. accept(conn)
  64. # Read from connections.
  65. for name, conn in users.items():
  66. try:
  67. message = conn.recv(1024)
  68. except socket.error:
  69. continue
  70. if not message:
  71. # Empty string is given on disconnect.
  72. del users[name]
  73. broadcast(name, "--- %s leaves ---" % name)
  74. else:
  75. broadcast(name, "%s> %s" % (name, message.strip()))
  76. time.sleep(.1)
  77. except (SystemExit, KeyboardInterrupt):
  78. break

Report this snippet  

You need to login to post a comment.