obernardovieira

Chatroom [Server]

Sep 23rd, 2016
355
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. #This is just an example not prepared to warn other clients when one leave the chatroom and not even when it's empty
  2. #just connect and talk. It's for an article at my wordpress.
  3. #Check the complete aticle at http://obernardovieira.byethost18.com
  4. #client side here http://pastebin.com/SXnqHTyU
  5.  
  6. # Echo server program
  7. import socket
  8. from threading import Thread
  9.  
  10. all_conns = []
  11.  
  12. def sendToAll(data):
  13.     for conn in all_conns:
  14.         conn.sendall(data)
  15.  
  16. def talkToClient(conn, addr):
  17.     print 'Connected by', addr
  18.     while 1:
  19.         data = conn.recv(1024)
  20.         if not data: break
  21.         sendToAll(data);
  22.     conn.close()
  23.  
  24. HOST = 'localhost'        # Symbolic name meaning all available interfaces
  25. PORT = 50007              # Arbitrary non-privileged port
  26. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  27. s.bind((HOST, PORT))
  28. s.listen(1)
  29.  
  30. while 1:
  31.     conn, addr = s.accept()
  32.     all_conns.append(conn)
  33.     Thread(target=talkToClient, args=(conn,addr,)).start()
Add Comment
Please, Sign In to add comment