Reputation: 61
I need to connect to two websockets servers simultaneously using python, as I need to amalgamate the data received from each into one file and then process it. I have used something like the following successfully for one websockets feed, but can't get it to work for two feeds simultaneously:
from websocket import create_connection
ws_a = create_connection("wss://www.server1.com")
ws_a.send("<subscription message, server 1>")
ws_b = create_connection("wss://www.server2.com")
ws_b.send("<subscription message, server 2>")
while bln_running:
response_a = ws_a.recv()
if "success" in response_a:
...do something...
response_b = ws_b.recv()
if "success" in response_b:
...do something...
However, in this example, I receive events from only server 1. I don't think splitting it into two threads will work, as I then have two different sets of data, and I need them amalgamated. (Although challenging this statement is a possible alternative solution???)
Any guidance or advice on getting both feeds simultaneously appreciated.
Many thanks.
My python version: 3.6.2 |Anaconda custom (64-bit)| (default, Sep 19 2017, 08:03:39) [MSC v.1900 64 bit (AMD64)]
Upvotes: 2
Views: 2123
Reputation: 61
This worked:
from websocket import create_connection
from threading import Lock, Thread
lock = Lock()
message_list = [] #global list
def collect_server1_data():
global message_list
bln_running = True
ws_a = create_connection("wss://www.server1.com")
ws_a.send("<subscription>")
while bln_running:
response_a = ws_a.recv()
lock.acquire()
message_list.append(response_a)
lock.release()
response_a = ""
def collect_server2_data():
global message_list
bln_running = True
ws_b = create_connection("wss://www.server2.com")
ws_b.send("<subscription>")
while bln_running:
response_b = ws_b.recv()
lock.acquire()
message_list.append(response_b)
lock.release()
response_b = ""
### --------Main--------
threads = []
for func in [collect_server1_data, collect_server2_data]:
threads.append(Thread(target=func))
threads[-1].start()
for thread in threads:
thread.join()
Thanks to JohanL for the steer in the right direction.
Upvotes: 4