Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 10th, 2012  |  syntax: None  |  size: 1.13 KB  |  hits: 22  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Simple telnet chat server in Python
  2. Trying 192.168.1.3...
  3. telnet: connect to address 192.168.1.3: Connection refused
  4. telnet: Unable to connect to remote host
  5.        
  6. import socket, threading
  7.  
  8. HOST = '127.0.0.1'
  9. PORT = 51234
  10.  
  11. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  12. s.bind((HOST, PORT))
  13. s.listen(4)
  14. clients = [] #list of clients connected
  15. lock = threading.Lock()
  16.  
  17.  
  18. class chatServer(threading.Thread):
  19.     def __init__(self, (socket,address)):
  20.         threading.Thread.__init__(self)
  21.         self.socket = socket
  22.         self.address= address
  23.  
  24.     def run(self):
  25.         lock.acquire()
  26.         clients.append(self)
  27.         lock.release()
  28.         print '%s:%s connected.' % self.address
  29.         while True:
  30.             data = self.socket.recv(1024)
  31.             if not data:
  32.                 break
  33.             for c in clients:
  34.                 c.socket.send(data)
  35.         self.socket.close()
  36.         print '%s:%s disconnected.' % self.address
  37.         lock.acquire()
  38.         clients.remove(self)
  39.         lock.release()
  40.  
  41. while True: # wait for socket to connect
  42.     # send socket to chatserver and start monitoring
  43.     chatServer(s.accept()).start()