|
3 | 3 | # Distributed under the MIT software license, see the accompanying
|
4 | 4 | # file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
5 | 5 |
|
6 |
| -# A blocking example using python 2.7 can be obtained from the git history: |
7 |
| -# https://github.com/bitcoin/bitcoin/blob/37a7fe9e440b83e2364d5498931253937abe9294/contrib/zmq/zmq_sub.py |
| 6 | +""" |
| 7 | + ZMQ example using python3's asyncio |
| 8 | +
|
| 9 | + Bitcoin should be started with the command line arguments: |
| 10 | + bitcoind -testnet -daemon \ |
| 11 | + -zmqpubhashblock=tcp://127.0.0.1:28332 \ |
| 12 | + -zmqpubrawtx=tcp://127.0.0.1:28332 \ |
| 13 | + -zmqpubhashtx=tcp://127.0.0.1:28332 \ |
| 14 | + -zmqpubhashblock=tcp://127.0.0.1:28332 |
| 15 | +
|
| 16 | + We use the asyncio library here. `self.handle()` installs itself as a |
| 17 | + future at the end of the function. Since it never returns with the event |
| 18 | + loop having an empty stack of futures, this creates an infinite loop. An |
| 19 | + alternative is to wrap the contents of `handle` inside `while True`. |
| 20 | +
|
| 21 | + The `@asyncio.coroutine` decorator and the `yield from` syntax found here |
| 22 | + was introduced in python 3.4 and has been deprecated in favor of the `async` |
| 23 | + and `await` keywords respectively. |
| 24 | +
|
| 25 | + A blocking example using python 2.7 can be obtained from the git history: |
| 26 | + https://github.com/bitcoin/bitcoin/blob/37a7fe9e440b83e2364d5498931253937abe9294/contrib/zmq/zmq_sub.py |
| 27 | +""" |
8 | 28 |
|
9 |
| -import array |
10 | 29 | import binascii
|
11 |
| -import asyncio, zmq, zmq.asyncio |
| 30 | +import asyncio |
| 31 | +import zmq |
| 32 | +import zmq.asyncio |
12 | 33 | import signal
|
13 | 34 | import struct
|
14 | 35 | import sys
|
@@ -56,16 +77,13 @@ def handle(self) :
|
56 | 77 | asyncio.ensure_future(self.handle())
|
57 | 78 |
|
58 | 79 | def start(self):
|
59 |
| - asyncio.ensure_future(self.handle()) |
| 80 | + self.loop.add_signal_handler(signal.SIGINT, self.stop) |
| 81 | + self.loop.create_task(self.handle()) |
60 | 82 | self.loop.run_forever()
|
61 | 83 |
|
62 | 84 | def stop(self):
|
63 | 85 | self.loop.stop()
|
64 | 86 | self.zmqContext.destroy()
|
65 | 87 |
|
66 | 88 | daemon = ZMQHandler()
|
67 |
| -def signal_handler(num, frame): |
68 |
| - daemon.stop() |
69 |
| - exit(0) |
70 |
| -signal.signal(signal.SIGINT, signal_handler) |
71 | 89 | daemon.start()
|
0 commit comments