0

我已经使用扭曲的示例(进行了一些修改)设置了一个 TCP 服务器。

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

import yaml

class User(LineReceiver):
    def __init__(self,users):
        self.users = users
        self.name = None

    def connectionMade(self):
        print 'new connection'
        self.sendLine('username:')

    def connectionLost(self,reason):
        print 'connection lost'
        if not self.name == None:
            msg = '%s has disconnected' % (self.name)
            print msg
            self.toAll(msg,None)
            del self.users[self.name]

    def lineRecieved(self,line):
        print line
        if self.name == None:
            self.setName(line)
        else:
            self.toChat(line)

    def toAll(self,msg,to_self):
        for name, protocol in self.users.iteritems():
            if protocol == self and not to_self == None:
                self.sendLine(to_self)
            else:
                protocol.sendLine(msg)

    def setName(self,name):
        if self.users.has_key(name):
            self.sendLine('username in use')
            return
        elif ' ' in name:
            self.sendLine('no spaces!')
            return
        print 'new user %s' % (name)
        self.sendLine('logged in as %s' % (name))
        self.name = name
        self.users[name] = self

    def toChat(self,message):
        msg = '<%s> %s' % (self.name,message)
        print msg
        to_self = '<%s (you)> %s' % (self.name,message)
        self.toAll(msg,to_self)


class Main(Factory):
    def __init__(self,motd=None):
        self.users = {}
        self.motd = motd
        print 'loaded, waiting for connections...'

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

if not path.isfile('config.yml'):
    open('config.yml','w').write('port: 4444\nmotd: don\'t spam')

with open('config.yml','r') as f:
    dump = yaml.load(f.read())
    motd = dump['motd']
    port = dump['port']

reactor.listenTCP(port,Main(motd=motd))
reactor.run()

我想知道如何才能连接到它?我已经尝试调整他们的示例 Echo 客户端和 Echo 服务器,但我的服务器仅在将数据发送回它时才会出现巨大错误。

(回声服务器在这里,回声客户端在这里

我正在使用的客户端是

from twisted.internet import reactor
from twisted.internet.protocol import Protocol,ClientFactory

class Main(Protocol):
    def dataReceived(self,data):
        print data
        self.transport.write(data)

class MainFactory(ClientFactory):
    def buildProtocol(self,addr):
        print 'connected'
        return Main()

    def clientConnectionLost(self,connector,reason):
        print 'connection lost'

    def clientConnectionFailed(self,connector,reason):
        print 'connection failed'

reactor.connectTCP('localhost',4444,MainFactory())
reactor.run()

这是错误的图片

错误图片

我需要做什么才能将数据发送回服务器?我需要从哪个类继承?

4

1 回答 1

3

问题是一个简单的错字。

LineReceiver在每一行调用它的lineReceived方法。你应该覆盖它。但你没有,lineRecieved而是你定义。因此,您将获得默认实现,即 raise NotImplemented.


如果你解决了这个问题,你的代码仍然有点奇怪。通过通信跟踪。

客户端连接,它调用服务器的User.connectionMade,它执行以下操作:

self.sendLine('username:')

所以客户得到它Main.dataReceived并这样做:

self.transport.write(data)

因此,它会将提示作为响应发回。

服务器将接收它lineReceived(一旦您修复了名称)并执行以下操作:

if self.name == None:
    self.setName(line)

因此,您要将用户名设置为'username:'.

于 2013-07-12T23:15:42.107 回答