连接到Twisted TCP服务器

时间:2013-07-12 22:56:00

标签: python twisted

我已经使用扭曲的示例(经过一些修改)设置了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服务器,但我的服务器只在发送回数据时发出巨大错误。

(echo服务器为here,echo客户端为here

我使用的客户是

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()

这是错误的图片

Image of error

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

1 个答案:

答案 0 :(得分:3)

这个问题很简单。

LineReceiver在每一行调用lineReceived方法。你应该覆盖它。但是你不这样做,而是定义lineRecieved。因此,您将获得默认实现,该实现会引发NotImplemented


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

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

self.sendLine('username:')

所以客户端在Main.dataReceived中获取并执行此操作:

self.transport.write(data)

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

服务器将在lineReceived(一旦您修改名称)中收到该内容并执行此操作:

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

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