I have the following basic code, which connects to a websocket server and receives some data:
import websocket, json, time
def process_message(ws, msg):
message = json.loads(msg)
print(message)
def on_error(ws, error):
print('Error', e)
def on_close(ws):
print('Closing')
def on_open(ws):
def run(*args):
Subs = []
tradeStr= """{"method": "SUBSCRIBE", "params":%s, "id": 1}"""%(json.dumps(Subs))
ws.send(tradeStr)
thread.start_new_thread(run, ())
def Connect():
websocket.enableTrace(False)
ws = websocket.WebSocketApp("wss://myurl", on_message = process_message, on_error = on_error, on_close = on_close)
ws.on_open = on_open
ws.run_forever()
Connect()
Now, I would like to create more connections to different servers and receive data concurrently in the same script. I tried the following:
def run(url):
def process_message(ws, msg):
message = json.loads(msg)
print(message)
def on_error(ws, error):
print('Error', e)
def on_close(ws):
print('Closing')
def on_open(ws):
def run(*args):
Subs = []
tradeStr= """{"method": "SUBSCRIBE", "params":%s, "id": 1}"""%(json.dumps(Subs))
ws.send(tradeStr)
thread.start_new_thread(run, ())
def Connect():
websocket.enableTrace(False)
ws = websocket.WebSocketApp(url, on_message = process_message, on_error = on_error, on_close = on_close)
ws.on_open = on_open
ws.run_forever()
Connect()
threading.Thread(target=run, kwargs={'url': 'url1'}).start()
threading.Thread(target=run, kwargs={'url': 'url2'}).start()
threading.Thread(target=run, kwargs={'url': 'url3'}).start()
Now, this code works, but I'm connecting to different URLs and I'm streaming data from all of them, but it seemed to me an "hacky" solution. I also don't know if what I'm doing could be bad practice or not. Each connection will send around 600/700 small JSON dictionaries, and I need to update every record to the db.
So my question is: is this implementation ok? Since it works with threads, can it create problems in the long run? Should I do another library such as Tornado?
websockets
here: github.com/aaugustin/websockets#why-should-i-use-websockets \$\endgroup\$