skynyrd
skynyrd

Reputation: 982

Adding private chat functionality to simple twisted chat server

I am trying to learn twisted library from its documentation. I've created a simple chat server that allows users to public chat. However, I wonder if I can add private chat functionality to that. I am looking for your ideas. Thanks.

from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor

class Chat(LineReceiver):
    def __init__(self,users):
        self.users = users
        self.name = None
        self.state = "GETNAME"

    def connectionMade(self):
        self.sendLine("What's your name?")

    def connectionLost(self, reason):
        if self.users.has_key(self.name):
            del self.users[self.name]

    def lineReceived(self,line):
        if self.state == "GETNAME":
            self.handle_GETNAME(line)
        else:
            self.handle_CHAT(line)

    def handle_GETNAME(self,name):
        if self.users.has_key(name):
            self.sendLine("Name taken, please choose another.")
            return
        self.sendLine("Welcome, %s!" % (name))
        self.name = name
        self.users[name] = self
        self.state = "CHAT"

    def handle_CHAT(self,msg):
        msg = "<%s> %s" % (self.name,msg)
        for name,protocol in self.users.iteritems():
            if protocol != self:
                protocol.sendLine(msg)

class ChatFactory(Factory):
    def __init__(self):
        self.users = {}
    def buildProtocol(self, addr):
        return Chat(self.users)

reactor.listenTCP(8123,ChatFactory())  #@UndefinedVariable
reactor.run() #@UndefinedVariable

Upvotes: 2

Views: 1349

Answers (1)

skynyrd
skynyrd

Reputation: 982

Actually I figured it out by changing the for loop in handle_CHAT. As I want the program to send the message to the specific user, a "talkwith" string can be added to the class and this string can hold that specific user's name. Then this change turns the program from public to private chatting.

msg = "<%s> %s" % (self.name,msg)
            for name,protocol in self.users.iteritems():
                if name == self.talkwith:
                    protocol.sendLine(msg)

Upvotes: 1

Related Questions