[英]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. 我需要使用python同时连接到两个websockets服务器,因为我需要将从每个接收到的数据合并到一个文件中,然后进行处理。 I have used something like the following successfully for one websockets feed, but can't get it to work for two feeds simultaneously:
我已经对一个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...
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. 但是,在此示例中,我仅从服务器1接收事件。我不认为将其拆分为两个线程是可行的,因为这样我将拥有两组不同的数据,因此需要将它们合并。 (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)| 我的python版本:3.6.2 | Anaconda自定义(64位)| (default, Sep 19 2017, 08:03:39) [MSC v.1900 64 bit (AMD64)]
(默认值,2017年9月19日,08:03:39)[MSC v.1900 64位(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. 感谢JohanL的正确指导。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.