0

尽管这个问题可能看起来很简单,但我无法找到一种可行的方式或无论如何打印来自线程 websocket 的传入消息。

基本上,我创建了一个 jupyterlab 笔记本,可以让我连接到本地 websocket 服务器并回显从 firecamp websocket 连接发送的消息。在单元格上运行它时(没有运行按钮和运行A.start()),我可以看到打印件,但是在重新启动内核后按下运行按钮后,我就看不到传入的消息。

通常我会期待这样的事情:

Function started
Someone said: test 1
Someone said: test 2

在打印中,但点击运行按钮时似乎没有任何东西出现。

主要目标是能够运行带有voila的笔记本以上传到heroku,但我似乎无法使打印工作。如果有人有线索或更好的主意,我会全神贯注。

提前致谢。

PD:代码

import ipywidgets as widgets
from IPython.display import Javascript, display
import websocket
import asyncio
import nest_asyncio
import threading
import websocket
import time
import sys
import trace
import logging
from time import sleep

output_box = widgets.Output()
class KThread(threading.Thread):
    """A subclass of threading.Thread, with a kill() method."""  
    def __init__(self, *args, **keywords):
        threading.Thread.__init__(self, *args, **keywords)
        self.killed = False

    def start(self):        
        """Start the thread."""
        self.__run_backup = self.run
        self.run = self.__run     
        threading.Thread.start(self)

    def __run(self):
        """Hacked run function, which installs the trace."""
        sys.settrace(self.globaltrace)
        self.__run_backup()
        self.run = self.__run_backup

    def globaltrace(self, frame, why, arg):
        if why == 'call':
          return self.localtrace
        else:
          return None

    def localtrace(self, frame, why, arg):
        if self.killed:
          if why == 'line':
            raise SystemExit()
        return self.localtrace

    def kill(self):
        ws.close()
        self.killed = True
def on_message(ws, message):    
    print(message)
def on_open(ws):
    ws.send("Connected Test")
def on_close(ws, close_status_code, close_msg):
    print("### closed ###")
def on_error(ws, error):
    print(error)
#This illustrates running a function in a separate thread. The thread is killed before the function finishes.
def func():    
    print('Function started')
    ws.run_forever()

ws = websocket.WebSocketApp("ws://localhost:7890", on_open=on_open,on_message = on_message, on_close = on_close,on_error = on_error)
A = KThread(target=func)

websocket.enableTrace(True)
run_button = widgets.Button(
    description='Run Button',
    disabled=False,
    button_style='info', # 'success', 'info', 'warning', 'danger' or ''
    tooltip='Run button function',
    icon='play'
)

def on_run_button_clicked(b):
    with output_box:
        A.start()       
run_button.on_click(on_run_button_clicked)
display(run_button,output_box)

这是 websocket 服务器:

# Importing the relevant libraries
import websockets
import asyncio

# Server data
PORT = 7890
print("Server listening on Port " + str(PORT))

# A set of connected ws clients
connected = set()

# The main behavior function for this server
async def echo(websocket, path):
    print("A client just connected")
    # Store a copy of the connected client
    print(websocket)
    connected.add(websocket)
    # Handle incoming messages
    try:
        async for message in websocket:
            print("Received message from client: " + message)
            # Send a response to all connected clients except sender
            for conn in connected:                
                if conn != websocket:
                    await conn.send("Someone said: " + message)
    # Handle disconnecting clients 
    except websockets.exceptions.ConnectionClosed as e:
        print("A client just disconnected")
    finally:
        connected.remove(websocket)

# Start the server
start_server = websockets.serve(echo, "localhost", PORT)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
4

0 回答 0