我想添加一个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数据包?

最佳答案

添加它。

您要做的就是不要两次调用reactor.run()reactor.run()是Twisted中的阻止API(在程序结束之前一直阻止)。

关于python - 我可以将Twisted GTK Reactor与UDP接收器一起使用吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23329589/

10-12 21:41