如何在brython中创建websocket JSObject?

时间:2013-07-29 07:13:44

标签: javascript python html5 websocket brython

所以我试图在brython中使用websockets,这是python3的一个javascript实现。不幸的是,我没有太多运气。

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

ws = JSObject(WebSocket("ws://echo.websocket.org/"))ws = JSObject(new WebSocket("ws://echo.websocket.org/"))似乎都无效。

我发现文件py_websocket.js文件是brython“站点镜像”下载的一部分,但仍然无法实现。

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

1 个答案:

答案 0 :(得分:4)

以下是使用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>

代码应该是不言自明的。需要完成有关Web套接字的更多文档的Brython站点