Python3 Websockets / Multithreading issue

2019-08-10 17:39发布

A little BG information on my application:

I am writing an application to stream data from a python script to a webbrowser. I am planning on streaming the data using the WebSocket module in Python3. I am streaming large amounts of data and I want to be able to start and stop the streaming at the user's leisure. My initial plan is to have two python3 websocket servers running. One to recieve commands from the web page (The "commander") and one to stream the data based on the commands recieved. This however requires a few things that I am unclear about.

1.) How so I run two Websocket Servers in the same python script, see below

I am using the Python3 Websockets module with no issues whatsoever using the following code:

import asyncio
import websockets
import sys
import time
import multiprocessing


@asyncio.coroutine
def commander_start(websocket,path):
    while True:
        command = yield from websocket.recv()
        if command == 'log':
            print("Log Recieved...")
            #Set global variable or queue
        if command == 'stop':
            print("Stop Received...")
            #Set global variable or queue

def run_commander():
    start_commander = websockets.serve(commander_start,'localhost',5001)
    asyncio.get_event_loop().run_until_complete(start_commander)
    asyncio.get_event_loop().run_forever()

@asyncio.coroutine
def logger(websocket,path):
    a = 0
    while True:
        #Check global variable, if not set, then exit
        print("Logger Test: %d" % a)
        a += 1

def run_logger():
    start_logger = websockets.serve(logger,'localhost',5002)
    asyncio.get_event_loop().run_until_complete(start_logger)
    asyncio.get_event_loop().run_forever()

def main():
    commander = multiprocessing.Process(target=run_commander)
    commander.start()

if __name__ == "__main__":
    main()

This works perfectly fine...however I want to be able to run the logger at the same time. When I add the following to main:

logger_thread = multiprocessing.Logger(target=run_logger)
logger_thread.start()

The logger server never starts, I'm guessing that I am not properly understanding the way that the Python3 Websockets module works.

Ideally I would like to be able to start both my commander_start and logger websockets and share a variable between them.

2.) How can I share a queue of information between these two threads? Assuming of course that I can run them each in their own thread given the constraints that I am currently working out in problem 1.)

I am not sure where to go from here and feel like I'm hitting a brick wall.

0条回答
登录 后发表回答