Pau*_*aul 4 html javascript python websocket brython
我正在尝试使用Brython在浏览器中运行 Python 代码,并在该 Python 代码中使用 websockets。
我有工作的 JavaScript 代码,可以连接到位于http://www.websocket.org/echo.html的 Websocket echo 服务器。
根据文档,该函数JSObject可用于操作 Brython 中的 JavaScript 对象,但我无法使用 或 使其ws = JSObject(WebSocket("ws://echo.websocket.org/"))工作ws = JSObject(new WebSocket("ws://echo.websocket.org/"))。
如何使用 Brython 在 Python 代码中制作一个连接到 echo 服务器的简单“Hello World”示例?
另请参阅如何使用 Brython 导入库以使用未内置于 Brython 的库(包括常用的 Python 标准库)。
小智 5
以下是使用 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>
Run Code Online (Sandbox Code Playgroud)
该代码应该是不言自明的。Brython 站点需要补充更多有关 Web 套接字的文档
| 归档时间: |
|
| 查看次数: |
675 次 |
| 最近记录: |