Frequently asked questions

Syntax, keywords and built-in functions

Standard distribution

import implementation

Browser interface

Brython-specific built-in modules

Working with Brython

Brython for Firefox OS



module browser.websocket

Web sockets, defined in HTML5, are a way to handle bi directional communication between client and server

The module defines a boolean:

indicates if the protocol is supported by the browser

and a function:

host is the location of a server that supports the WebSocket protocol. Returns a WebSocket object. If the browser doesn't support WebSocket, a NotImplementedError will be raised

WebSocket objects have the following methods :

attaches the function to the event evt. The events and the corresponding function arguments are :

Event Function
open function with no argument, called once the connection with the server is established
error function with no argument, called if an error occurs during the communication
message function that takes one argument, an instance of DOMEvent. This instance has an attribute data that holds the message sent by the server as a string
close function with no argument, called when the connection is closed

sends the string data to the server

closes the connection

Example :

from browser import alert, document as doc
from browser import websocket

def on_open(evt):
    doc['sendbtn'].disabled = False
    doc['closebtn'].disabled = False
    doc['openbtn'].disabled = True

def on_message(evt):
    # message reeived from server
    alert("Message received : %s"

def on_close(evt):
    # websocket is closed
    alert("Connection is closed")
    doc['openbtn'].disabled = False
    doc['closebtn'].disabled = True
    doc['sendbtn'].disabled = True

ws = None
def _open(ev):
    if not websocket.supported:
        alert("WebSocket is not supported by your browser")
    global ws
    # open a web socket
    ws = websocket.WebSocket("wss://")
    # bind functions to web socket events

def send(ev):
    data = doc["data"].value
    if data:

def close_connection(ev):
    doc['openbtn'].disabled = False

doc['openbtn'].bind('click', _open)
doc['sendbtn'].bind('click', send)
doc['closebtn'].bind('click', close_connection)