class SessionProtocol(protocol.Protocol):

    SHELL = "\r\nCastle-%s-%d:%02d:%02d>> "

    def __init__(self, factory):
        self._telnet = TelnetService(self)
        self._session = Session(self)
        self._factory = factory
        self._locate = ""

    def connectionMade(self):
        self.transport.write(WELCOME_MESSAGE)
        self._session.handle("")

    def dataReceived(self, data):
        cmd = self._telnet.handle(data)
        if cmd:
            if self._session.logged():
                pbproxy = self._factory["player"]
                if pbproxy:
                    pbproxy.callRemote("handle", self._session._name,
                                       pickle.dumps(cmd)).\
                        addCallback(self._cmdResult)
                else:
                    self._protocol.transport.write("\r\n用戶服务器未启动!\r\n")
                    self._protocol.transport.loseConnection()

            else:
                self._session.handle(cmd)

    def _cmdResult(self, result):
        self.writeShell(result)

    def writeShell(self, data):
        if data:
            self.transport.write("\r\n")
            self.transport.write(str(data))

        lt = time.localtime()
        self.transport.write(SessionProtocol.SHELL %
                             (self._locate, lt.tm_hour, lt.tm_min, lt.tm_sec))

    def connectionLost(self, reason):
        self._session.logout()
 def __init__(self, factory):
     self._telnet = TelnetService(self)
     self._session = Session(self)
     self._factory = factory
     self._locate = ""