繁体   English   中英

我可以在python中同时连接到两个不同的websockets服务器吗?

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

我需要使用python同时连接到两个websockets服务器,因为我需要将从每个接收到的数据合并到一个文件中,然后进行处理。 我已经对一个websockets feed成功地使用了以下类似的方法,但是不能同时用于两个feed:

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...

但是,在此示例中,我仅从服务器1接收事件。我不认为将其拆分为两个线程是可行的,因为这样我将拥有两组不同的数据,因此需要将它们合并。 (尽管挑战此声明是一种可能的替代解决方案???)

有关同时获得两个供稿的任何指导或建议。

非常感谢。

我的python版本:3.6.2 | Anaconda自定义(64位)| (默认值,2017年9月19日,08:03:39)[MSC v.1900 64位(AMD64)]

这工作:

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

感谢JohanL的正确指导。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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