[Twisted-Python] AMP with a long-lived connection - results and deferred?
Oon-Ee Ng
ngoonee.talk at gmail.com
Thu Oct 29 02:16:38 MDT 2015
And lo and behold it seems to work now even with Kivy. Strange. For
posterity, here's the simple client code I was using for a minimal
example. I'll expand upwards from here and see how far I can get.
#install_twisted_rector must be called before importing the reactor
from kivy.support import install_twisted_reactor
install_twisted_reactor()
from twisted.internet import reactor, protocol
from twisted.internet.task import deferLater
from ampserver import Sum, Divide
from twisted.protocols import amp
class EchoClient(amp.AMP):
def connectionMade(self):
self.factory.resetDelay()
self.factory.app.on_connection(self)
class EchoFactory(protocol.ReconnectingClientFactory):
protocol = EchoClient
def __init__(self, app):
self.app = app
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
# A simple kivy App, with a textbox to enter messages, and
# a large label to display all the messages received from
# the server
class TwistedClientApp(App):
connection = None
def build(self):
root = self.setup_gui()
self.connect_to_server()
return root
def setup_gui(self):
self.textbox = TextInput(size_hint_y=.1, multiline=False)
self.textbox.bind(on_text_validate=self.send_message)
self.label = Label(text='connecting...\n')
self.layout = BoxLayout(orientation='vertical')
self.layout.add_widget(self.label)
self.layout.add_widget(self.textbox)
return self.layout
def connect_to_server(self):
reactor.connectTCP('127.0.0.1', 1234, EchoFactory(self))
def on_connection(self, connection):
self.print_message("connected succesfully!")
self.connection = connection
def send_message(self, *args):
msg = self.textbox.text.encode('ascii')
if self.connection:
d = self.connection.boxReceiver.callRemote(Sum, a=3, b=8)
def prin(result):
print(result)
d.addCallback(prin)
def print_message(self, msg):
self.label.text += str(msg) + "\n"
if __name__ == '__main__':
TwistedClientApp().run()
More information about the Twisted-Python
mailing list