WebSockets

Server

This section delves into the intricacies of utilizing WebSockets within the Radiant and Tornado ecosystem. It’s crucial to understand that WebSockets functionality is integrated within Tornado, and not directly within Radiant (Brython). To effectively incorporate WebSockets in a Radiant-based application, one must establish a WebSocketHandler within the Tornado framework. For a comprehensive understanding of the WebSocketHandler class and its implementation, refer to the Tornado documentation.

[ ]:
#ws_handler.py

from tornado.websocket import WebSocketHandler

class WSHandler(WebSocketHandler):

    def open(self):
        ...

    def on_close(self):
        ...

    def on_message(self, message):
        ...

To integrate a WebSocketHandler in your RadiantServer, it can be passed as a parameter to the websockethandler during server creation. This process effectively bridges Radiant and Tornado, allowing for WebSocket functionalities within your Radiant application.

[ ]:
RadiantServer('MainApp', websockethandler=('ws_handler.py', 'WSHandler'))

Creating a WebSocket server in this context involves setting up a listener on a specified URL, such as /ws. To define the WebSocketHandler class, pass a tuple that includes the path to the module and the class name. For example, if your module is ws_handler.py and the class is WSHandler, this information should be specified accordingly.

Client

For constructing a WebSocket client in a Brython environment, the browser.websocket module is utilized. The following example demonstrates the procedure to create a WebSocket client, leveraging Brython’s capabilities.

[ ]:
from browser import websocket

def on_open(evt):
    print('Connection opened.')

def on_message(evt):
    print('Message received:', evt.data)

def on_close(evt):
    print('Connection closed.')

ws = websocket.WebSocket('ws://localhost:8888/ws')
ws.bind('open', on_open)
ws.bind('message', on_message)
ws.bind('close', on_close)

In the demonstrated example, a new WebSocket object is instantiated and connected to the server using ws://localhost:8888/ws as the URL. Event handlers for open, message, and close events are then bound to this WebSocket. Upon opening the connection, the on_open function is triggered, and similarly for other events. The URL in the WebSocket constructor can be modified to align with your server’s specifics, and the event handlers can be tailored to manage the data received from the server.