invisibleroads / invisibleroads/socketIO-client
asyncio - How to properly implement an async pub/sub client
- Dominant language
- Python
- Stars
- 441
- Forks
- 204
- PR merge metrics
- No merged PRs in 30d
Description
I read through the issue posted by @F483 [here](https://github.com/invisibleroads/socketIO-client/issues/80), which was ultimately solved by making the blocking wait() call on recv() for 1 second. Given that this is still a blocking call, how would one properly implement an asyncio version (or any type of simple asynchronous methodology) on the code below with limited library exposure? I am having considerable trouble finding a reasonable and simple example for what seems to be a straightforward question. Days of searching. Any help would be greatly appreciated - I'm new to socket development and especially to async frameworks.
Here's F483's example code:
```
import time
import threading
from socketIO_client import SocketIO
class TestSubscribe():
def connect(self):
baseurl = "http://v1.livenet.bitcoin.chromanode.net"
self._socketIO = SocketIO(baseurl, 80)
self._socketIO.on('new-block', self.on_newblock)
self._socketIO.emit('subscribe', 'new-block')
self._socketIO_thread = threading.Thread(target=self._socketIO.wait)
self._socketIO_thread.start()
def on_newblock(self, blockid, blockheight):
print "new-block:", blockid, blockheight
# add to input queue for further processing
def disconnect(self):
# XXX works ... badly
print "disconnect before:", self._socketIO.connected
self._socketIO.disconnect()
self._socketIO_thread.join() # takes quite some time
print "disconnect after:", self._socketIO.connected # still connected?
self._socketIO = None
self._socketIO_thread = None
testsubscribe = TestSubscribe()
testsubscribe.connect()
time.sleep(10)
testsubscribe.disconnect()
```
My attempt below (skeleton code..similar to what I have implemented in a project) simply stalls upon calling _socketIO.wait()...
```
import time
from socketIO_client import SocketIO
class TestSubscribe():
async def connect(self):
baseurl = "http://v1.livenet.bitcoin.chromanode.net"
self._socketIO = SocketIO(baseurl, 80)
self._socketIO.on('new-block', self.on_newblock)
self._socketIO.emit('subscribe', 'new-block')
await self._socketIO.wait() #stops here, if I get it to end, then returns None type (bad). how does one properly coroutine this?
async def on_newblock(self, blockid, blockheight):
print "new-block:", blockid, blockheight
# add to input queue for further processing
async def disconnect(self):
# XXX works ... badly
print "disconnect before:", self._socketIO.connected
await self._socketIO.disconnect()
print "disconnect after:", self._socketIO.connected # still connected?
self._socketIO = None
testsubscribe = TestSubscribe()
testsubscribe.connect()
time.sleep(10)
testsubscribe.disconnect() #can't get anything out of here...
```
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.