Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from twisted.internet import protocol, reactor
- from twisted.protocols import basic
- class Presence(basic.LineReceiver):
- def connectionMade(self):
- self.state = 'needlogin'
- def lineReceived(self, line):
- cmd, data = line.split(" ", 1)
- f = getattr(self, 'handle_%s' % cmd)
- f(data)
- def handle_LOGIN(self, username):
- if self.state != 'needlogin':
- self.sendLine('ERROR')
- return
- if self.factory.userOnline(username):
- self.sendLine('NO')
- else:
- self.factory.addUser(username)
- self.username = username
- self.sendLine('YES')
- self.state = 'loggedin'
- def handle_ISONLINE(self, username):
- if self.state != 'loggedin':
- self.sendLine('ERROR')
- return
- if self.factory.userOnline(username):
- self.sendLine('YES')
- else:
- self.sendLine('NO')
- def connectionLost(self, reason):
- if self.state == 'loggedin':
- u = self.username
- self.factory.removeUser(u)
- class PresenceFactory(protocol.ServerFactory):
- # used by default buildProtocol:
- protocol = Presence
- def __init__(self):
- self.users = {}
- def addUser(self, user):
- self.users[user] = 1
- def removeUser(self, user):
- del self.users[user]
- def userOnline(self, user):
- return self.users.has_key(user)
- f = PresenceFactory()
- reactor.listenTCP(9123, f)
- reactor.run()
- ######### Nash chat fail:
- """The most basic chat protocol possible.
- run me with twistd -y chatserver.py, and then connect with multiple
- telnet clients to port 1025
- """
- from twisted.protocols import basic
- class MyChat(basic.LineReceiver):
- people = 0
- def connectionMade(self):
- print "Got new client!"
- MyChat.people += 1
- self.transport.write("Welcome new client!" + str(MyChat.people) + '\n')
- #self.factory.clients.id = int(MyChat.people)
- self.factory.usernameId = MyChat.people
- self.factory.clients1.append(self)
- def connectionLost(self, reason):
- print "Lost a client!"
- MyChat.people -= 1
- self.factory.clients1.remove(self)
- def lineReceived(self, line):
- print "received", repr(line)
- self.factory.clients1[2].message(line)
- if line == "show":
- c.message(str(MyChat.people)) #prints number of clients for the client asking
- if line == "myid":
- c.message(str(self.factory.usernameId)) #prints number of clients for the client asking
- def message(self, message):
- self.transport.write(message + '\n')
- from twisted.internet import protocol
- from twisted.application import service, internet
- factory = protocol.ServerFactory()
- factory.protocol = MyChat
- factory.clients1 = []
- application = service.Application("chatserver")
- internet.TCPServer(1025, factory).setServiceParent(application)
Add Comment
Please, Sign In to add comment