为什么telnetlib写函数不能在我的python代码中工作?

时间:2013-11-01 04:29:19

标签: python twisted telnetlib

我正在学习python几个星期,我正在尝试构建一个聊天应用程序,我选择了扭曲并感觉很舒服,但我在客户端测试代码中遇到了一个奇怪的问题。

这是我的服务器代码:

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

class ChatServer(LineReceiver):

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

    def connectionMade(self):
        self.sendLine("What's your name?")
        print 'DEBUG: Name Input Request Send Back To Client.'

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

    def lineReceived(self, line):
        print 'DEBUG: A Message Recieved From Client.'
        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,))
        print 'DEBUG: Welcome Message Send Back To Client.'
        self.name = name
        self.users[name] = self
        self.state = "CHAT"

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

class ChatServerFactory(Factory):

    def __init__(self):
        self.users = {}

    def buildProtocol(self, addr):
        return ChatServer(self.users)

reactor.listenTCP(8123, ChatServerFactory())
reactor.run()

这是我的客户端测试代码,我试图以telnet的方式测试服务器。

import telnetlib
import cmd
import sys
import time

def test_telnet(Host, Port):     
    # connected to the server
    tn = telnetlib.Telnet(Host, Port)  
    print 'Client Connecton Made.'
    # tn.set_debuglevel(2)

    # read back from server
    greeting = tn.read_until("What's your name?")
    print 'Recieved Name Input Request From Server'
    print greeting
    print "DEBUG: Before telnet write data"
    username = 'amber'
    tn.write(username + '\n')
    print "DEBUG: After telnet write data"
    # welcome = tn.read_until('see', 5)
    # print 'Recieved Welcome Message From Server'
    # print welcome

    time.sleep(7)
    tn.write("exit\n")
    print 'Client Connection Lost.'

test_telnet('localhost', 8123)

然而,tn.write()发送消息,但是在服务器控制台中,我注意到lineReceived永远不会被调用,但是在实际的telnet中,它被调用,为什么呢? 非常感谢!

1 个答案:

答案 0 :(得分:2)

LineReceiver预计行以\r\n结尾,而不是\n

使用\n替换代码中的\r\n可以解决问题。


或者,您可以更改行分隔符:

class ChatServer(LineReceiver):
    delimiter = '\n' # <----
    ...