In this post, we’re stepping into the universe of real-time communications with WebSocket routing.
Total.js v5: Simple WebSocket Routing
Welcome back to our Beginner's Guide to Total.js! In our previous post, we explored standard routing, setting the foundation for handling HTTP requests. If you haven’t read it yet, be sure to check it out to get the basics of how routing works in Total.js.
In this post, we’re stepping into the universe of real-time communication with WebSocket routing. WebSockets enable two-way communication between the client and server, making them ideal for applications that require instantaneous data flow like chat apps, live notifications, and real-time updates.
What are webSockets and why are they important?
WebSockets allow for full-duplex communication between the client and server. This means that after the initial connection, both parties can send and receive messages at any time, without having to make new HTTP requests. This differs from the traditional request/response model where the client has to request information, and the server responds.
WebSockets are perfect for scenarios where real-time updates are crucial, such as:
- Chat applications: Where messages need to be sent and received instantly.
- Live notifications: Where updates (like new emails or alerts) need to be pushed to the user without them refreshing the page.
- Collaborative tools: Where users can work together on documents or projects in real time.
With Total.js, setting up WebSocket routing is simple and flexible. You can define routes that allow your application to handle WebSocket connections efficiently.
WebSocket routing in Total.js v5
Supported Flags
When setting up WebSocket routes in Total.js v5, you can specify different types of communication using flags:
@json
: Communicates in JSON format (default).@text
: Communicates using plain text.@binary
: Communicates using binary data (useful for file transfers, images, etc.).
These flags give you control over how data is sent and received during the WebSocket session. Now, let's dive into how WebSocket routing works in practice.
Setting Up a Basic WebSocket Route
To get started with WebSocket routing, you define a SOCKET
route in your controllers
folder, similar to how we define HTTP routes. Let’s look at a basic example where we use plain text communication.
Here’s the basic setup:
Explanation:
- WebSocket Route: The
ROUTE('SOCKET / @text <1MB', socket)
defines a WebSocket route at/
with a communication type of plain text (@text
). The<1MB
part limits the maximum size of a message to 1 MB.
- Connections: The
$.connections
object holds all the active WebSocket connections. Each client is assigned an ID, and you can use this to send messages to specific clients or broadcast messages to all clients.
- Lifecycle Events:
- open: Fired when a client connects to the WebSocket server. Here, we greet the client by sending
"Hello world"
. - message: Fired when a client sends a message. The message is logged to the console, and we reply by echoing it back.
- close: Fired when the client disconnects from the WebSocket server. We simply log that the client disconnected.
- open: Fired when a client connects to the WebSocket server. Here, we greet the client by sending
- Automatic Cleanup: We use
$.autodestroy()
to automatically clean up the controller when no clients are connected.
This example demonstrates the basics of handling WebSocket connections, managing clients, and sending messages.
Example: Real-Time Chat Application
Let’s build on this by creating a simple real-time chat example, where multiple clients can connect and send messages that are broadcasted to all connected users.
How It Works:
- Chat Route: We define a WebSocket route at
/chat/
that communicates via JSON (@json
).
- Broadcast Function: The
broadcast
function sends a message to all connected clients except the sender. This ensures that every user in the chat receives messages from other users.
- Message Handling:
- When a client connects, a message is broadcast to all other clients notifying them that a new user has joined.
- When a client sends a message, it is broadcast to all other connected users in real-time.
- When a client disconnects, a message is broadcast indicating that a user has left the chat.
Testing the WebSocket Server
To test the WebSocket server, you can use any WebSocket client, like Postman or a browser-based tool like WebSocket King. You can also write a simple HTML client to connect and communicate with the server.
Here’s a basic HTML client for testing:
Steps:
- Connect to the WebSocket server at
ws://localhost:8000/chat/
. - Send messages by typing into the input field and clicking the "Send" button. Messages are broadcast to all other connected users.
- Receive messages from other users, which are displayed in real time.
Conclusion
WebSockets provide an incredibly powerful way to add real-time communication to your web applications. With Total.js v5, you can easily set up WebSocket routes to handle text, JSON, or binary data, and create applications that need real-time updates, like chat systems, live dashboards, and collaborative tools.
In this post, we’ve covered:
- The basics of WebSocket routing in Total.js.
- How to handle events like
open
,message
, andclose
. - How to build a simple chat application using WebSockets.
Stay tuned for next part, where we’ll explore more advanced topics like WebSocket dynamic routing!
Thanks for reading, and as always, feel free to experiment and take your WebSocket applications to the next level!
Other posts from Total.js Platform
- 2024-12-10Total.js UI Builder: How to upload files?
- 2024-12-04Performance Testing: Total.js vs. Koa
- 2024-12-03Total.js UI Builder: Creating a Form
- 2024-12-02November report 2024
- 2024-11-26Total.js V5: Schemas and Actions
- 2024-11-25QueryBuilder in Action Part 1
- 2024-11-13Benchmarking Node.js Frameworks: selecting your framework for 2025!
- 2024-11-01October report 2024
- 2024-10-22Performance Testing: Total.js vs. NestJS
- 2024-10-01September report 2024