2012-12-09 153 views
0

我想建立一个简单的“引用当日”服务器和客户端从扭曲的教程文档修改。我想从客户那里打印“当天的报价单”以证明沟通。但是,从我可以告诉客户没有连接。这是我的代码。蟒蛇扭曲简单的服务器客户端

服务器

from twisted.python import log 
from twisted.internet.protocol import Protocol 
from twisted.internet.protocol import Factory 
from twisted.internet.endpoints import TCP4ServerEndpoint 
from twisted.internet import reactor 

class QOTD(Protocol): 
    def connectionMade(self): 
     self.transport.write("An apple a day keeps the doctor away\r\n") 
     self.transport.loseConnection() 

class QOTDFactory(Factory): 
    def buildProtocol(self, addr): 
     return QOTD() 

# 8007 is the port you want to run under. Choose something >1024 
endpoint = TCP4ServerEndpoint(reactor, 8007) 
endpoint.listen(QOTDFactory()) 
reactor.run() 

客户

import sys 
from twisted.python import log 
from twisted.internet import reactor 
from twisted.internet.protocol import Factory, Protocol 
from twisted.internet.endpoints import TCP4ClientEndpoint 

class SimpleClient(Protocol): 
    def connectionMade(self): 
     log.msg("connection made") 
     #self.transport.loseConnection() 

    def lineReceived(self, line): 
     print "receive:", line 

class SimpleClientFactory(Factory): 
    def buildProtocol(self, addr): 
     return SimpleClient() 

def startlog(): 
    log.startLogging(sys.stdout) 

point = TCP4ClientEndpoint(reactor, "localhost", 8007) 
d = point.connect(SimpleClientFactory) 
reactor.callLater(0.1, startlog) 
reactor.run() 

回答

2
  • SimpleClientFactory的传球实例,而不是类本身,如果point.connect()
  • 子类的SimpleClient从twisted.protocol.basic.LineReceiver而不是协议你用lineReceived
  • endpoint.listenpoint.connect的结果调用addErrback来处理错误
+0

它是LineReceiver的子类化,它使它工作。谢谢! –