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

a. The open Event

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.

b. The message Event

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.

c. The error Event

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.

d. The close Event

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:

  1. Connection Established (open event):

    • The client opens a connection to the server.
    • The server and client are now ready to communicate.
  2. 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.
  3. 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.
  4. 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:

Step 1: Create a WebSocket Server (server.js)

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.

  1. Connection Open: Observe the message when a connection is made.
  2. Message: Send messages between clients, and see the messages broadcasted.
  3. Error: Simulate a network issue by disconnecting the server, and watch for the error event.
  4. 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:

  1. When a client connects, the server sends a welcome message using the open event.
  2. When a client sends a message, the server listens for it via the message event and then broadcasts it to all other connected clients.
  3. If thereโ€™s a network issue, handle it with the error event to show an error message to the user.
  4. When a client disconnects, the server triggers the close event and cleans up the connection.

๐Ÿ“Œ 7. Conclusion

Key Takeaways:

  • The open, message, error, and close 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.