2

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

这是我的服务器代码:

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 中,它会被调用,这是为什么呢?非常感谢!

4

1 回答 1

2

LineReceiver期望行以 结尾\r\n,而不是\n

\n将代码替换为\r\n解决问题。


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

class ChatServer(LineReceiver):
    delimiter = '\n' # <----
    ...
于 2013-11-01T05:19:49.767 回答