I'm, getting WebSocket data from a website, code is written in
python
and usesautobahn
,twisted
,threading
for WebSocket handling. The process followsws.subscribe(<list>)
for subscribing to different items andws.unsubscribe(<list>)
to unsubscribe and show data usingon_message()
.I want to create a local server which will serve the data got in step 1 (Kind of relay server, I hope). The flow I'm thinking:
a. local client(s) will request for subscription to local server.
b. local server based on the subscribe/unsubscribe request received from local client(s), it will subscribe to actual server (step 1).
c. whenever any message received from actual server, local server will send data based on subscription(s) to local clients.
Step 1 code:
from MainServer import MainDataService
mds = MainDataService(
user_id='user_id',
apikey='APIKEY')
)
def on_connect(ws, response):
# settings subscribed, need to change based on local subscribe request
ws.subscribe(['demand'])
def on_message(ws, payload, is_binary):
# getting the message here, that need to relay based on local subscribe
if is_binary:
print(_parse_binary(payload))
else:
print(_parse_text_message(payload))
mds.on_connect = on_connect
mds.on_message = on_message
mds.connect(threaded=True)
How to achieve this, what to use? Any guide/code will be helpful.
Edit 1: This is probably related to crossbar.io, PUB/SUB, relay, WAMP, router.
Edit 2: What I have done:
started crossbar router: crossbar init
, crossbar start
.
pub.py
from autobahn.asyncio.component import Component
from asyncio import sleep
from autobahn.asyncio.component import run
component = Component(
transports=u"ws://localhost:8080/ws",
realm=u"realm1",
)
@component.on_join
async def joined(session, details):
print("session ready")
counter = 0
while True:
session.publish(u'com.myapp.oncounter', counter)
counter += 1
await sleep(1)
if __name__ == "__main__":
run([component])
sub.py
from autobahn.asyncio.component import Component
from autobahn.asyncio.component import run
component = Component(
transports=u"ws://localhost:8080/ws",
realm=u"realm1",
)
@component.subscribe(u"com.myapp.oncounter")
def oncounter(count):
print("event received: {0}", count)
if __name__ == "__main__":
run([component])
pub.py
and sub.py
working perfectly. But, I need to code session.publish
dynamically, as described in "Step 2". That means when any client(s) subscribe
to demand
or oncounter
only then publish.