Events - potatoscript/websocket GitHub Wiki
๐ฏ WebSocket Events
๐ 1. What Are WebSocket Events?
When using WebSockets, the client and server can communicate in real-time. WebSocket events allow you to listen for specific actions or trigger events. For example, we can listen for when a client connects, disconnects, sends a message, or encounters an error. These events help us manage real-time communication.
WebSocket events weโll cover:
- open
- message
- error
- close
๐๏ธ 2. Basic WebSocket Events
open
Event
a. The The open
event is triggered when the WebSocket connection is successfully established between the client and the server. This event is useful when you want to confirm that the connection is open and ready to send messages.
Example:
const ws = new WebSocket("ws://localhost:3000");
ws.onopen = function() {
console.log("โ
Connection Established!");
};
Explanation:
ws.onopen
is triggered when the WebSocket connection is open.- We display a success message when the connection is established.
message
Event
b. The The message
event is triggered when the server sends a message to the client. You can use this event to display the message to the user or handle incoming data.
Example:
const ws = new WebSocket("ws://localhost:3000");
ws.onmessage = function(event) {
console.log(`๐ฉ Message from server: ${event.data}`);
};
Explanation:
ws.onmessage
triggers every time the server sends a message.- The
event.data
contains the message sent from the server.
error
Event
c. The The error
event is triggered when thereโs a problem with the WebSocket connection, such as network issues or unexpected server behavior. You can use this event to log errors or handle issues gracefully.
Example:
const ws = new WebSocket("ws://localhost:3000");
ws.onerror = function(error) {
console.log(`โ ๏ธ WebSocket Error: ${error}`);
};
Explanation:
ws.onerror
triggers whenever there's an issue with the WebSocket.- The
error
object provides information about the error.
close
Event
d. The The close
event is triggered when the WebSocket connection is closed, either by the server or the client. You can use this event to clean up resources or notify the user about the closure.
Example:
const ws = new WebSocket("ws://localhost:3000");
ws.onclose = function() {
console.log("โ Connection Closed");
};
Explanation:
ws.onclose
is triggered when the WebSocket connection is closed.- This could be due to an intentional disconnection or a network issue.
๐ 3. Complete Example with All WebSocket Events
Letโs integrate all four events (open
, message
, error
, close
) into one complete WebSocket client example:
const ws = new WebSocket("ws://localhost:3000");
// Open Event
ws.onopen = function() {
console.log("โ
Connection Opened!");
ws.send("Hello Server! ๐");
};
// Message Event
ws.onmessage = function(event) {
console.log(`๐ฉ Message from Server: ${event.data}`);
};
// Error Event
ws.onerror = function(error) {
console.log(`โ ๏ธ WebSocket Error: ${error}`);
};
// Close Event
ws.onclose = function() {
console.log("โ Connection Closed");
};
๐ 4. WebSocket Event Flow
Hereโs a simple flow of how events happen:
-
Connection Established (
open
event):- The client opens a connection to the server.
- The server and client are now ready to communicate.
-
Message Sent/Received (
message
event):- Both the client and server can send messages to each other.
- The
onmessage
event is triggered every time a message is received.
-
Error Occurs (
error
event):- If thereโs a problem (like network failure), the
error
event will be triggered. - You can handle this event to inform the user or attempt to reconnect.
- If thereโs a problem (like network failure), the
-
Connection Closed (
close
event):- Either the client or server closes the WebSocket connection.
- You can perform any necessary cleanup, like saving data or informing the user.
๐งโ๐ป 5. Complete WebSocket Server with Events
Letโs take a look at how we can handle WebSocket events on the server side using Node.js and the ws
package:
server.js
)
Step 1: Create a WebSocket Server (const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3000 });
// Event when a new client connects
wss.on('connection', function(ws) {
console.log("๐ A new client connected!");
// Send a welcome message to the client
ws.send("๐ Welcome to the WebSocket server!");
// Listen for messages from clients
ws.on('message', function(message) {
console.log(`๐ฉ Received: ${message}`);
// Broadcast the message to all clients
wss.clients.forEach(function(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(`๐ข ${message}`);
}
});
});
// Handle close event
ws.on('close', function() {
console.log("โ A client disconnected.");
});
// Handle error event
ws.on('error', function(error) {
console.log(`โ ๏ธ Error occurred: ${error}`);
});
});
Step 2: Test the WebSocket Server
To test, open multiple browser tabs with the WebSocket client you created in the previous section, and observe the events triggered in the console.
- Connection Open: Observe the message when a connection is made.
- Message: Send messages between clients, and see the messages broadcasted.
- Error: Simulate a network issue by disconnecting the server, and watch for the error event.
- Close: Close a client and observe the message when the client disconnects.
๐ฏ 6. Using WebSocket Events to Build Real-Time Applications
Example Use Case: Real-Time Chat Application
With WebSocket events, you can build real-time applications like chat apps where messages are sent and received instantly. Hereโs a simple plan for your app:
- When a client connects, the server sends a welcome message using the
open
event. - When a client sends a message, the server listens for it via the
message
event and then broadcasts it to all other connected clients. - If thereโs a network issue, handle it with the
error
event to show an error message to the user. - When a client disconnects, the server triggers the
close
event and cleans up the connection.
๐ 7. Conclusion
Key Takeaways:
- The
open
,message
,error
, andclose
events are essential for managing WebSocket connections. - Use the
message
event to receive and broadcast messages. - Handle errors properly to provide a better user experience.
- Clean up connections on disconnect to avoid memory leaks.