如何在brython中创建websocketjsobject?

2024-04-29 16:26:31 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我尝试在brython中使用websockets,这是python3的javascript实现。不幸的是,我运气不好。在

根据文档,函数JSObject()可以用于操作brython中的JS对象,但我在websockets中没有这方面的运气。我正试图用echoserver:http://www.websocket.org/echo.html(当我使用javascript代码时,它工作得很好)。在

ws = JSObject(WebSocket("ws://echo.websocket.org/"))和{}似乎都不起作用。在

我发现了一个文件py_websocket.js文件作为brython“site mirror”下载的一部分,但是仍然无法实现它。在

我不确定这是否只是没有实现,或者我在使用brython的JSObject()时遗漏了一个重要的概念。在


Tags: 文件对象函数文档orgechowswebsockets
1条回答
网友
1楼 · 发布于 2024-04-29 16:26:31

下面是一个使用py乩websocket中包含的内置websocket()函数和服务器的示例echo.websocket.org公司名称:

<html>
<head>
<meta charset="iso-8859-1">
<script src="/src/brython.js"></script>

<script type="text/python3">
def on_open():
    # Web Socket is connected, send data using send()
    data = doc["data"].value
    if data:
        ws.send(data)
        alert("Message is sent")

def on_message(evt):
    # message received from server
    alert("Message received : %s" %evt.data)

def on_close(evt):
    # websocket is closed
    alert("Connection is closed")

ws = None
def _test():
    global ws
    # open a web socket
    ws = websocket("wss://echo.websocket.org")
    # attach functions to web sockets events
    ws.on_open = on_open
    ws.on_message = on_message
    ws.on_close= on_close

def close_connection():
    ws.close()
</script>
</head>
<body onload="brython(1)">
<input id="data">
<button onclick="_test()">Run WebSocket</button>
<p><button onclick="close_connection()">Close connection</button>
</body>
</html>

代码应该是自解释的。Brython站点需要用更多关于web套接字的文档来完成

相关问题 更多 >