|
1 |
| -import json |
2 | 1 | import logging
|
3 | 2 | import threading
|
4 |
| -from urllib.parse import urlparse |
5 |
| -from twisted.internet import reactor, ssl |
6 |
| -from twisted.internet.error import ReactorAlreadyRunning |
7 |
| -from autobahn.twisted.websocket import WebSocketClientFactory, connectWS |
8 |
| -from binance.websocket.binance_client_protocol import BinanceClientProtocol |
9 |
| -from binance.websocket.binance_client_factory import BinanceClientFactory |
| 3 | +from websocket import ( |
| 4 | + ABNF, |
| 5 | + create_connection, |
| 6 | + WebSocketException, |
| 7 | + WebSocketConnectionClosedException, |
| 8 | +) |
10 | 9 |
|
11 | 10 |
|
12 | 11 | class BinanceSocketManager(threading.Thread):
|
13 |
| - def __init__(self, stream_url): |
| 12 | + def __init__( |
| 13 | + self, |
| 14 | + stream_url, |
| 15 | + on_message=None, |
| 16 | + on_open=None, |
| 17 | + on_close=None, |
| 18 | + on_error=None, |
| 19 | + on_ping=None, |
| 20 | + on_pong=None, |
| 21 | + logger=None, |
| 22 | + ): |
14 | 23 | threading.Thread.__init__(self)
|
15 |
| - |
16 |
| - self.factories = {} |
17 |
| - self._connected_event = threading.Event() |
| 24 | + if not logger: |
| 25 | + logger = logging.getLogger(__name__) |
| 26 | + self.logger = logger |
18 | 27 | self.stream_url = stream_url
|
19 |
| - self._conns = {} |
20 |
| - self._user_callback = None |
21 |
| - |
22 |
| - def _start_socket( |
23 |
| - self, stream_name, payload, callback, is_combined=False, is_live=True |
24 |
| - ): |
25 |
| - if stream_name in self._conns: |
26 |
| - return False |
27 |
| - |
28 |
| - if is_combined: |
29 |
| - factory_url = self.stream_url + "/stream" |
30 |
| - else: |
31 |
| - factory_url = self.stream_url + "/ws" |
32 |
| - |
33 |
| - if not is_live: |
34 |
| - payload_obj = json.loads(payload.decode("utf8")) |
35 |
| - |
36 |
| - if is_combined: |
37 |
| - factory_url = factory_url + "?streams=" + payload_obj["params"] |
38 |
| - else: |
39 |
| - factory_url = factory_url + "/" + payload_obj["params"] |
40 |
| - payload = None |
41 |
| - |
42 |
| - logging.info("Connection with URL: {}".format(factory_url)) |
| 28 | + self.on_message = on_message |
| 29 | + self.on_open = on_open |
| 30 | + self.on_close = on_close |
| 31 | + self.on_ping = on_ping |
| 32 | + self.on_pong = on_pong |
| 33 | + self.on_error = on_error |
| 34 | + self.create_ws_connection() |
43 | 35 |
|
44 |
| - factory = BinanceClientFactory(factory_url, payload=payload) |
45 |
| - factory.base_client = self |
46 |
| - factory.protocol = BinanceClientProtocol |
47 |
| - factory.setProtocolOptions( |
48 |
| - openHandshakeTimeout=5, autoPingInterval=300, autoPingTimeout=5 |
| 36 | + def create_ws_connection(self): |
| 37 | + self.logger.debug( |
| 38 | + "Creating connection with WebSocket Server: %s", self.stream_url |
49 | 39 | )
|
50 |
| - factory.callback = callback |
51 |
| - self.factories[stream_name] = factory |
52 |
| - reactor.callFromThread(self.add_connection, stream_name, self.stream_url) |
| 40 | + self.ws = create_connection(self.stream_url) |
| 41 | + self.logger.debug( |
| 42 | + "WebSocket connection has been established: %s", self.stream_url |
| 43 | + ) |
| 44 | + self._callback(self.on_open) |
53 | 45 |
|
54 |
| - def add_connection(self, stream_name, url): |
55 |
| - if not url.startswith("wss://"): |
56 |
| - raise ValueError("expected wss:// URL prefix") |
| 46 | + def run(self): |
| 47 | + self.read_data() |
57 | 48 |
|
58 |
| - factory = self.factories[stream_name] |
59 |
| - options = ssl.optionsForClientTLS(hostname=urlparse(url).hostname) |
60 |
| - self._conns[stream_name] = connectWS(factory, options) |
| 49 | + def send_message(self, message): |
| 50 | + self.logger.debug("Sending message to Binance WebSocket Server: %s", message) |
| 51 | + self.ws.send(message) |
61 | 52 |
|
62 |
| - def stop_socket(self, conn_key): |
63 |
| - if conn_key not in self._conns: |
64 |
| - return |
| 53 | + def ping(self): |
| 54 | + self.ws.ping() |
65 | 55 |
|
66 |
| - # disable reconnecting if we are closing |
67 |
| - self._conns[conn_key].factory = WebSocketClientFactory(self.stream_url) |
68 |
| - self._conns[conn_key].disconnect() |
69 |
| - del self._conns[conn_key] |
| 56 | + def read_data(self): |
| 57 | + data = "" |
| 58 | + while True: |
| 59 | + try: |
| 60 | + op_code, frame = self.ws.recv_data_frame(True) |
| 61 | + except WebSocketException as e: |
| 62 | + if isinstance(e, WebSocketConnectionClosedException): |
| 63 | + self.logger.error("Lost websocket connection") |
| 64 | + else: |
| 65 | + self.logger.error("Websocket exception: {}".format(e)) |
| 66 | + raise e |
| 67 | + except Exception as e: |
| 68 | + self.logger.error("Exception in read_data: {}".format(e)) |
| 69 | + raise e |
70 | 70 |
|
71 |
| - def run(self): |
72 |
| - try: |
73 |
| - reactor.run(installSignalHandlers=False) |
74 |
| - except ReactorAlreadyRunning: |
75 |
| - # Ignore error about reactor already running |
76 |
| - pass |
| 71 | + if op_code == ABNF.OPCODE_CLOSE: |
| 72 | + self.logger.warning( |
| 73 | + "CLOSE frame received, closing websocket connection" |
| 74 | + ) |
| 75 | + self._callback(self.on_close) |
| 76 | + break |
| 77 | + elif op_code == ABNF.OPCODE_PING: |
| 78 | + self._callback(self.on_ping, frame.data) |
| 79 | + self.ws.pong("") |
| 80 | + self.logger.debug("Received Ping; PONG frame sent back") |
| 81 | + elif op_code == ABNF.OPCODE_PONG: |
| 82 | + self.logger.debug("Received PONG frame") |
| 83 | + self._callback(self.on_pong) |
| 84 | + else: |
| 85 | + data = frame.data |
| 86 | + if op_code == ABNF.OPCODE_TEXT: |
| 87 | + data = data.decode("utf-8") |
| 88 | + self._callback(self.on_message, data) |
77 | 89 |
|
78 | 90 | def close(self):
|
79 |
| - keys = set(self._conns.keys()) |
80 |
| - for key in keys: |
81 |
| - self.stop_socket(key) |
82 |
| - self._conns = {} |
| 91 | + if not self.ws.connected: |
| 92 | + self.logger.warn("Websocket already closed") |
| 93 | + else: |
| 94 | + self.ws.send_close() |
| 95 | + return |
| 96 | + |
| 97 | + def _callback(self, callback, *args): |
| 98 | + if callback: |
| 99 | + try: |
| 100 | + callback(self, *args) |
| 101 | + except Exception as e: |
| 102 | + self.logger.error("Error from callback {}: {}".format(callback, e)) |
| 103 | + if self.on_error: |
| 104 | + self.on_error(self, e) |
0 commit comments