# Telnet Chat Server # ------------------------------------------------------------- # Clients connect in on telnet through port 24800. They enter the # word "SPIROU" (minus the quotes.) The server then asks them to # enter a username. They are now free to chat. # # Released under the GPLv3. This was the product of a few hours of # boredom - I realize it's pretty horrible code. from time import sleep from threading import Thread from twisted.internet.protocol import Protocol, Factory from twisted.protocols.basic import LineReceiver from twisted.internet import reactor port = 24800 password = "SPIROU" messagesToDistribute = list() class Chat(LineReceiver): def __init__(self): self.username = "" self.passwordvalid = False self.killthread = False msgCheckThread(self).start() self.blockmsg = list() def lineReceived(self, line): if line.upper() == 'QUIT' or line.upper() == 'EXIT': self.sendLine("Goodbye...") print "Client quit " + self.transport.getHost().host + " / " + self.username self.transport.loseConnection() self.killthread = True elif self.passwordvalid == False: global password if line.upper() == password: self.passwordvalid = True self.sendLine("Password Correct.") self.transport.write("Please enter a name to identify yourself by: ") print "Client entered correct password." else: print "Client " + self.transport.getHost().host + " tried password \"" + line + "\" which was incorrect." elif self.username == "": self.sendLine("") self.sendLine("Welcome " + line + "...") print "Client setting name as " + line self.sendLine("Enter \"QUIT\" to exit the application.") self.sendLine("") self.username = line else: global messageToDistribute if line == "": messagesToDistribute.append("") else: self.blockmsg.append(len(messagesToDistribute)) messagesToDistribute.append(self.username + ": " + line) print "Received msg from " + self.username + ": " + line class msgCheckThread(Thread): def __init__ (self, chatClass): Thread.__init__(self) self.chatclass = chatClass def run(self): global messagesToDistribute self.msgIndex = len(messagesToDistribute) if self.chatclass.transport != None: print "Client at " + self.chatclass.transport.getHost().host + " connected" while self.chatclass.killthread == False: sleep(0.1) while self.msgIndex < len(messagesToDistribute): self.skip = False for blockedmsg in self.chatclass.blockmsg: if blockedmsg == self.msgIndex: self.skip = True if self.skip == False: print " Delivering to " + self.chatclass.transport.getHost().host + " / " + self.chatclass.username if messagesToDistribute[self.msgIndex] == "": self.chatclass.transport.write("") else: self.chatclass.sendLine(messagesToDistribute[self.msgIndex]) self.msgIndex += 1 self.chatclass.blockmsg = list() print "Server Started - Telnet to port " + str(port) + "..." factory = Factory() factory.protocol = Chat reactor.listenTCP(port, factory) reactor.run()