我可以使用带有UDP接收器的Twisted GTK Reactor吗?

时间:2014-04-27 22:01:18

标签: python gtk twisted

我想添加一个UDP接收器:

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor

class UDP(DatagramProtocol):

    def datagramReceived(self, data, (host, port)):
    #Receive a string "X Y" and add to plot.    
    print "Received %r from %s:%d" % (data, host, port)

reactor.listenUDP(9999, UDP())
reactor.run()

我现有的使用GTKReactor的matplotlib代码:

from matplotlib import use
use('GTK')
from matplotlib import pyplot
from matplotlib.backends import backend_gtk
from twisted.internet import gtk2reactor
gtk2reactor.install()

from twisted.internet import reactor, task

class TwistedGtkShow(backend_gtk.Show):
    running = False
    def mainloop(self):
        if not self.running:
            self.running = True
            reactor.run()

def onclick(event):
  print 'Clicked: %d, X=%d, Y=%d, Xdata=%f, Ydata=%f' % (event.button, event.x, event.y, event.xdata, event.ydata)

def onpress(event):
  print "Pressed: ", event.key


def main():
    fig = pyplot.figure()
    pyplot.plot([1,2,3,4])
    pyplot.ylabel('Numbers')

    cid = fig.canvas.mpl_connect('button_press_event', onclick)
    cid = fig.canvas.mpl_connect('key_press_event', onpress)

    def proof():
        print 'Twisted!'
    task.LoopingCall(proof).start(3)

    TwistedGtkShow()()

if __name__ == '__main__':
    main()

但他们都没有阻挡?如何运行它们并更新绘图以及响应单击事件并可能发回UDP数据包?

1 个答案:

答案 0 :(得分:1)

添加它。

所有你必须小心做的不是两次打电话reactor.run()reactor.run()是Twisted中的阻止API(在程序结束之前会阻塞)。