How can I create a websocket JSObject in brython?

Question:

I’m trying to use Brython to run Python code in the browser, and to use websockets in that Python code.

I have working JavaScript code that can connect to the Websocket echo server at http://www.websocket.org/echo.html.

According to the documentation, the function JSObject can be used to manipulate JavaScript objects in Brython, but I can’t get it to work using either ws = JSObject(WebSocket("ws://echo.websocket.org/")) or ws = JSObject(new WebSocket("ws://echo.websocket.org/")).

How can I make a simple "Hello World" example connecting to the echo server, in Python code, using Brython?


See also How to import library using Brython for using libraries that aren’t built in to Brython (including the usual Python standard library).

Asked By: Paul

||

Answers:

Here is an example using the built-in websocket() function, included in py_websocket, and the server 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>

The code should be self-explanatory. The Brython site needs to be completed with more documentation about web sockets

Answered By: marqueemoon