【问题标题】:How can I create a websocket JSObject in brython?如何在 brython 中创建 websocket JSObject?
【发布时间】:2013-07-28 21:18:25
【问题描述】:

所以我尝试在 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/")) 似乎都不起作用。

我在 brython 的“站点镜像”下载中找到了一个文件 py_websocket.js 文件,但仍然无法实现。

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

【问题讨论】:

    标签: javascript python html websocket brython


    【解决方案1】:

    这是一个使用内置 websocket() 函数的示例,包含在 py_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 套接字的文档

    【讨论】:

    • 谢谢,这完美地回答了我的问题。我没有意识到有一个内置的 websocket 功能 - 我无法在文档中找到它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多