使用twisted python

时间:2016-05-30 11:37:12

标签: python-2.7 twisted

我目前正在尝试使用Twisted Python的项目,我的问题特别是我尝试获取用户输入,同时还使用listenTCP()监听连接。我最初查找了这个问题,发现stdio.StandardIO似乎是最有效的方法,因为我已经在使用Twisted了。我也看到了在扭曲矩阵stdin.pystdiodemo.py上找到的代码示例,但是我正在努力解决如何将示例代码应用于我的特定问题,因为我需要从套接字读取并收集执行tcp任务时的用户输入。

我正在开发的项目规模要大得多,但是小的示例代码说明了我要做的事情,并隔离了我遇到的问题。任何帮助解决我的问题都非常感谢。

Server.py

from twisted.internet.protocol import Factory
from twisted.protocols import basic
from twisted.internet import reactor, protocol, stdio
from Tkinter import *
import os, sys

class ServerProtocol(protocol.Protocol):
    def __init__(self, factory):
        self.factory = factory
        stdio.StandardIO(self)

    def connectionMade(self):
        self.factory.numConnections += 1
        self.factory.clients.append(self)

    def dataReceived(self, data):
        try:
            print 'receiving data'
            print data
        except Exception, e:
            print e

    def connectionLost(self, reason):
        self.factory.numConnections -= 1
        self.factory.clients.remove(self)

class ServerFactory(Factory):
    numConnections = 0
    def buildProtocol(self, addr):
        return ServerProtocol(self)

class StdioCommandLine(basic.LineReceiver):
    from os import linesep as delimiter
    def connectionMade(self):
        self.transport.write('>>> ')
    def lineReceived(self, line):
        self.sendLine('Echo: ' + line)
        self.transport.write('>>> ')

reactor.listenTCP(9001, ServerFactory())
stdio.StandardIO(StdioCommandLine())
reactor.run()

Client.py

from twisted.internet import reactor, protocol
import os, time, sys
import argparse

class MessageClientProtocol(protocol.Protocol):

    def __init__(self, factory):
        self.factory = factory

    def connectionMade(self):
        self.sendMessage()

    def sendMessage(self):
        print 'sending message'
        try:
            self.transport.write('hello world')
        except e as Exception:
            print e

    def dataReceived(self, data):
        print 'received: ', data
        self.sendMessage()

class MessageClientFactory(protocol.ClientFactory):

    def __init__(self, message):
        self.message = message

    def buildProtocol(self, addr):
        return MessageClientProtocol(self)

    def clientConnectionFailed(self, connector, reason):
        print 'Connection Failed: ', reason.getErrorMessage()
        reactor.stop()

    def clientConnectionLost(self, connector, reason):
        print 'Connection Lost: ', reason.getErrorMessage()

reactor.connectTCP('192.168.1.70', 9001, MessageClientFactory('hello world - client'))
reactor.run()

目前上述代码返回Unhanded Error,如下所示。这演示了我使用stdin,然后将数据返回到stdout,连接的客户端导致错误:

  

python Server.py

     

>>>喂

     

Echo:你好

     

>>>未处理的错误回溯(最近一次调用最后一次):

     

文件   " /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twisted/python/log.py" ;,   第84行,在callWithContext

中      

return context.call({ILogContext:newCtx},func,* args,** kw)

     

文件   " /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twisted/python/context.py" ;,   第118行,在callWithContext中返回   self.currentContext()。callWithContext(ctx,func,* args,** kw)

     

文件   " /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twisted/python/context.py" ;,   第81行,在callWithContext

中      

return func(* args,** kw)

     

文件   " /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twisted/internet/selectreactor.py" ;,   第149行,在_doReadOrWrite

中      

why = getattr(selectable,method)()

     

---这里抓到的例外---

     

文件   " /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twisted/internet/tcp.py" ;,   第1067行,在doRead中   protocol = s

1 个答案:

答案 0 :(得分:0)

您提供的追溯似乎被切断了。我试图在我的机器上运行代码,它显示了这个回溯:

Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/twisted/python/log.py", line 84, in callWithContext
    return context.call({ILogContext: newCtx}, func, *args, **kw)
  File "/usr/lib/python2.7/site-packages/twisted/python/context.py", line 118, in callWithContext
    return self.currentContext().callWithContext(ctx, func, *args, **kw)
  File "/usr/lib/python2.7/site-packages/twisted/python/context.py", line 81, in callWithContext
    return func(*args,**kw)
  File "/usr/lib/python2.7/site-packages/twisted/internet/posixbase.py", line 597, in _doReadOrWrite
    why = selectable.doRead()
--- <exception caught here> ---
  File "/usr/lib/python2.7/site-packages/twisted/internet/tcp.py", line 1067, in doRead
    protocol = self.factory.buildProtocol(self._buildAddr(addr))
  File "Server.py", line 30, in buildProtocol
    return ServerProtocol(self)
  File "Server.py", line 10, in __init__
    stdio.StandardIO(self)
  File "/usr/lib/python2.7/site-packages/twisted/internet/_posixstdio.py", line 42, in __init__
    self.protocol.makeConnection(self)
  File "/usr/lib/python2.7/site-packages/twisted/internet/protocol.py", line 490, in makeConnection
    self.connectionMade()
  File "Server.py", line 14, in connectionMade
    self.factory.clients.append(self)
exceptions.AttributeError: ServerFactory instance has no attribute 'clients'

通过完整的回溯可以很容易地看到,工厂缺少client属性。这可以是固定的,例如将其添加到ServerFactory班级:

def __init__(self):
    self.clients = []