简体   繁体   中英

Can I connect to two different websockets servers simultaneously in python?

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)]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM