Added example

Fixed is_closed
This commit is contained in:
izderadicka
2016-05-21 12:31:52 +02:00
parent 5a72a46275
commit bb5f8bec7f
7 changed files with 195 additions and 3 deletions

View File

@@ -36,10 +36,25 @@ class PrefixProtocol(asyncio.Protocol):
self.log.debug('RawSocker Asyncio: Connection made with peer {peer}'.format(peer=self.peer))
self._buffer=b''
self._header=None
self._wait_closed=asyncio.Future()
@property
def is_closed(self):
if hasattr(self,'_wait_closed'):
return self._wait_closed
else:
f=asyncio.Future()
f.set_result(True)
return f
def connection_lost(self, exc):
self.log.debug('RawSocker Asyncio: Connection lost')
self.transport=None
self._wait_closed.set_result(True)
self._on_connection_lost(exc)
def _on_connection_lost(self,exc):
pass
def protocol_error(self, msg):
self.log.error(msg)
@@ -283,8 +298,7 @@ class WampRawSocketMixinAsyncio():
Base class for asyncio-based WAMP-over-RawSocket protocols.
"""
def connection_lost(self, exc):
def _on_connection_lost(self, exc):
try:
wasClean = exc is None
self._session.onClose(wasClean)

View File

@@ -61,7 +61,25 @@ class Test(TestCase):
receiver.assert_has_calls([call(b'abcd'), call(b'12345')])
self.assertEqual(p._buffer, b'\x00' )
def test_is_closed(self):
class CP(RawSocketClientProtocol):
@property
def serializer_id(self):
return 1
client=CP()
on_hs=Mock()
transport=Mock()
receiver=Mock()
client.stringReceived=receiver
client._on_handshake_complete=on_hs
self.assertTrue(client.is_closed.done())
client.connection_made(transport)
self.assertFalse(client.is_closed.done())
client.connection_lost(None)
self.assertTrue(client.is_closed.done())
def test_raw_socket_server1(self):
server=RawSocketServerProtocol(max_size=10000)

View File

@@ -248,8 +248,9 @@ class ApplicationRunnerRawSocket(object):
transport_factory = WampRawSocketClientFactory(create, serializer=self.serializer)
# 3) start the client
loop = asyncio.get_event_loop()
if logging_level=='debug':
loop.set_debug(True)
txaio.use_asyncio()
txaio.config.loop = loop
@@ -274,6 +275,7 @@ class ApplicationRunnerRawSocket(object):
# give Goodbye message a chance to go through, if we still
# have an active session
# it's not working now - because protocol is_closed must return Future
if protocol._session:
loop.run_until_complete(protocol._session.leave())

View File

@@ -0,0 +1,3 @@
/key.priv
/key.pub
/socket1

View File

@@ -0,0 +1,70 @@
{
"version": 2,
"workers": [
{
"type": "router",
"realms": [
{
"name": "realm1",
"roles": [
{
"name": "backend",
"permissions": [
{
"uri": "",
"match": "prefix",
"allow": {
"call": true,
"register": true,
"publish": true,
"subscribe": true
},
"disclose": {
"caller": false,
"publisher": false
},
"cache": true
}
]
}
]
}
],
"transports": [
{
"type":"rawsocket",
"endpoint": {
"type":"unix",
"path":"socket1"
},
"max_message_size": 16777216,
"auth":{
"anonymous": {
"type":"static",
"role":"backend"
}
}
},
{
"type":"rawsocket",
"endpoint": {
"type":"tcp",
"port":9090,
"interface": "127.0.0.1"
},
"max_message_size": 16777216,
"auth":{
"anonymous": {
"type":"static",
"role":"backend"
}
}
}
]
}
]
}

View File

@@ -0,0 +1,41 @@
import sys
import asyncio
from datetime import datetime
import os.path
import logging
log=logging.getLogger('backend')
sys.path=[os.path.join(os.path.dirname(__file__), '../../../..')]+sys.path
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunnerRawSocket
class MyComponent(ApplicationSession):
@asyncio.coroutine
def onJoin(self, details):
# a remote procedure; see frontend.py for a Python front-end
# that calls this. Any language with WAMP bindings can now call
# this procedure if its connected to the same router and realm.
def add2(x, y):
log.debug('add2 called with %s %s', x, y)
return x + y
yield from self.register(add2, u'com.myapp.add2')
# publish an event every second. The event payloads can be
# anything JSON- and msgpack- serializable
while True:
self.publish(u'com.myapp.hello', 'Hello, world! Time is %s'% datetime.utcnow())
log.debug('Published msg')
yield from asyncio.sleep(1)
if __name__ == '__main__':
level='info'
if len(sys.argv)>1 and sys.argv[1]=='debug':
level='debug'
path=os.path.join(os.path.dirname(__file__), '.crossbar/socket1')
runner = ApplicationRunnerRawSocket(
path,
u"realm1",
)
runner.run(MyComponent, logging_level=level)

View File

@@ -0,0 +1,44 @@
import asyncio
import sys
import logging
import os.path
log=logging.getLogger('frontend')
sys.path=[os.path.join(os.path.dirname(__file__), '../../../..')]+sys.path
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunnerRawSocket
from autobahn.wamp import ApplicationError
class MyComponent(ApplicationSession):
@asyncio.coroutine
def onJoin(self, details):
# listening for the corresponding message from the "backend"
# (any session that .publish()es to this topic).
def onevent(msg):
log.info("Got event: {}".format(msg))
yield from self.subscribe(onevent, u'com.myapp.hello')
# call a remote procedure.
count=0
while True:
try:
res = yield from self.call(u'com.myapp.add2', count, count+1)
log.info("Got result: {}".format(res))
except ApplicationError:
pass
count+=1
yield from asyncio.sleep(2)
if __name__ == '__main__':
level='info'
if len(sys.argv)>1 and sys.argv[1]=='debug':
level='debug'
runner = ApplicationRunnerRawSocket(
"tcp://localhost:9090",
u"realm1")
runner.run(MyComponent, logging_level=level)