WebSocket Methods, Events, and Functions
Front-end WebSocket (JavaScript) Methods, Properties, and Events
Constructor
The WebSocket
constructor is used to create a new WebSocket object, which represents a connection to a WebSocket server.
const socket = new WebSocket('ws://example.com/socket');
Properties
- WebSocket.readyState: Returns the current state of the connection.
0
: CONNECTING - The connection is not yet open.1
: OPEN - The connection is open and ready to communicate.2
: CLOSING - The connection is in the process of closing.3
: CLOSED - The connection is closed.
- WebSocket.bufferedAmount: Returns the number of bytes of data that have been queued but not yet transmitted to the network.
- WebSocket.binaryType: Indicates the type of binary data being transmitted. Default is
"blob"
. Can be set to"arraybuffer"
.
Methods
- WebSocket.send(data): Sends data to the server over the WebSocket connection. The
data
can be astring
,ArrayBuffer
,Blob
, orTypedArray
.socket.send('Hello Server');
- WebSocket.close(code, reason): Closes the WebSocket connection. The
code
is a numeric value indicating the status code explaining why the connection is being closed. Thereason
is a string providing additional information.socket.close(1000, 'Normal closure');
Events
WebSocket objects handle several types of events, allowing you to respond to changes in the connection state and incoming data.
- open: Triggered when the connection is successfully established.
socket.addEventListener('open', function (event) { console.log('Connected to the server'); });
- message: Triggered when data is received from the server.
socket.addEventListener('message', function (event) { console.log('Message from server ', event.data); });
- close: Triggered when the connection is closed.
socket.addEventListener('close', function (event) { console.log('Disconnected from the server'); });
- error: Triggered when there is an error with the connection.
socket.addEventListener('error', function (event) { console.error('WebSocket error observed:', event); });
Back-end WebSocket (FastAPI) Methods and Functions
Importing Required Modules
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
Connection Manager Class
This class manages active WebSocket connections and includes methods for connecting, disconnecting, and broadcasting messages.
class ConnectionManager:
def __init__(self):
self.active_connections = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
async def send_personal_message(self, message: str, websocket: WebSocket):
await websocket.send_text(message)
async def broadcast(self, message: str):
for connection in self.active_connections:
await connection.send_text(message)
Creating the WebSocket Endpoint
The WebSocket endpoint is defined as an asynchronous function that accepts WebSocket connections and handles incoming messages.
app = FastAPI()
manager = ConnectionManager()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await manager.send_personal_message(f"Echo: {data}", websocket)
except WebSocketDisconnect:
manager.disconnect(websocket)
await manager.broadcast("Client disconnected")
Handling WebSocket Events
The WebSocket class provides methods for receiving and sending text messages, as well as handling disconnections.
- await websocket.accept(): Accepts an incoming WebSocket connection.
- await websocket.receive_text(): Receives a text message from the WebSocket connection.
- await websocket.send_text(message): Sends a text message to the WebSocket connection.
- WebSocketDisconnect: Exception raised when a WebSocket connection is disconnected.