Chapter 36: WebSocket Basics in Elixir
Real-time bidirectional communication. In this chapter, you will learn websocket basics in depth with Elixir code examples, explanations, and best practices.
Overview
This chapter covers websocket basics for Kungfu.js developers using Elixir. We will start with the basics, move through practical examples, and end with advanced techniques and common pitfalls.
Why This Matters
Understanding websocket basics is essential because it is a core part of building web applications. Every real-world app needs to handle real-time bidirectional communication. Skipping this chapter would leave a gap in your knowledge that would cause problems later.
Code Example
Here is how to use WebSocket in Elixir:
// WebSocket is handled by the Rust core.
// Register a WebSocket handler:
app.ws('/chat', (ws) => {
ws.send('Welcome!');
ws.on('message', (msg) => {
ws.send('echo: ' + msg);
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
How WebSocket Works
WebSocket starts as a regular HTTP request with an Upgrade header. When the server sees this header, it responds with a 101 Switching Protocols status, and the TCP connection is "upgraded" to a bidirectional WebSocket connection.
After the upgrade, both client and server can send messages at any time. This is different from HTTP, where the client must request and the server must respond.
Common Mistakes
- Not reading the documentation: Always check the API reference when something does not work as expected.
- Skipping security: Never disable the default middleware unless you have a very good reason. Security is not optional.
- Not testing: Write tests for your handlers. Kungfu.js makes this easy with the built-in test utilities.
Summary
In this chapter, you learned about websocket basics in Elixir. You saw code examples, understood how things work under the hood, and learned about common mistakes to avoid.
What is Next?
In chapter 37, we will cover WebSocket Chat App: Build a live chat with WebSocket.