WebSocket
Handles real-time two-way connections in file-based routes.
WebSocket route
- server/routes/chat.ws.ts is /chat, room/index.ws.ts is /room, admin/log.ws.ts connects to /admin/log.
- Supports subfolders and [id], [[id]], [...path] dynamic paths.
- onOpen, onMessage, onClose and onError are automatically called when declared.
- Only files where active is true will receive a connection, and if auth is true, a login session will be created. Requests and provides a user to peer.user.
// server/routes/chat.ws.ts
export const config = {
active: false, // Sets whether to enable WebSocket routes.
auth: false, // Set whether only logged in users can connect.
sample: { message: "Hello from client!" } // JSON to send every 2 seconds in test
};
// Automatically called when a new WebSocket connection is opened.
export const onOpen = (peer: SocketPeer) => {
console.log("Connected:", peer.id);
};
// Called automatically when a message is received from the client.
export const onMessage = (peer: SocketPeer, message: SocketMessage) => {
console.log("Message:", message.text());
peer.send("Hello from server!");
};
// Automatically called when a WebSocket connection is terminated.
export const onClose = (
peer: SocketPeer,
details: SocketCloseDetails
) => {
console.log("Disconnected:", peer.id, details.code, details.reason);
};
// Automatically called when an error occurs during WebSocket processing.
export const onError = (peer: SocketPeer, error: Error) => {
console.error("Error:", peer.id, error);
};Message and connection limits
- Message size 64KB, idle termination 60 seconds, 100 simultaneous connections per route, 10 messages per second per connection is a Runtime internal fixed value.
- Messages exceeding 64KB are not delivered to the handler and are closed with close code 1009.
- If the message per second limit is exceeded, it closes with close code 1008.
- There is a maximum of 1,000 simultaneous connections across websites.
- Large files are sent as HTTP uploads rather than WebSocket messages.
Peer and message
- peer has id, params, request, user, remoteAddress, send, close, rooms, Provides join, leave and publish.
- message provides text(), json(), uint8Array(), and arrayBuffer().
- Join up to 20 rooms per connection with peer.join(room) Send across participating connections with await peer.publish(room, data).
- The room name must be 1 to 100 characters long, without spaces. Outgoing connections are also participating in rooms. You receive the message.
- In server data, rooms of multiple web processes can be accessed through Redis event streams. Synchronize and transfer local data to the current process.
- When the website restarts or terminates normally, the connection is closed with close code 1012.
- WebSocket connections do not automatically sleep while open. connection After everything is closed, it goes to sleep if there is no other HTTP, Task, or Queue job activity for 5 minutes.