> ## Documentation Index
> Fetch the complete documentation index at: https://docs.l2msg.com/llms.txt
> Use this file to discover all available pages before exploring further.

# WebSocket

The l2msg WhatsApp uses `socket.io` to emit real-time events, leveraging WebSocket technology. This makes integration development more efficient and straightforward for developers. WebSocket provides a full-duplex communication channel over a single, long-lasting connection, enabling real-time data flow between the client and the server.

## Operating

WebSocket can only be connected after executing the `set` command on the instance. This allows the WebSocket to be specific to each instance, and real-time communication is restricted to that instance.

* **Functionality**: Ideal for scenarios where you want more isolated real-time communication, focused on a single instance, allowing greater control and segmentation of events.

* **Connection**: WebSocket connection requires the use of `/instance_name` in the URL:

  ```plaintext theme={null}
  wss://api.l2msg.com/instance_name
  ```

## Connecting to the WebSocket

In traditional mode, use the following URL format:

```plaintext theme={null}
wss://api.l2msg.com/instance_name
```

Replace `instance_name` with your specific instance name.

### WebSocket Connection Example

Here is a basic example of how to establish a WebSocket connection using JavaScript:

```javascript theme={null}
const socket = io("wss://api.yoursite.com/instance_name", {
  transports: ["websocket"],
});

socket.on("connect", () => {
  console.log("Connected to the l2msg WhatsApp WebSocket");
});

// Listening to events
socket.on("event_name", (data) => {
  console.log("Event received:", data);
});

// Handling disconnection
socket.on("disconnect", () => {
  console.log("Disconnected from the l2msg WhatsApp WebSocket");
});
```

In this example, replace `event_name` with the specific event you want to listen to.

## Handling Events

Once connected, you can listen to various events emitted by the server. Each event can carry data relevant to the event's context. For instance, if you are listening for message updates, you may receive data containing the updated message content and metadata.

## Closing the Connection

To close the WebSocket connection, use the `disconnect` method:

```javascript theme={null}
socket.disconnect();
```

Remember to handle the connection responsibly by disconnecting when your application or component is unmounted to avoid memory leaks and ensure efficient resource usage.

## Final Considerations

The l2msg WhatsApp provides a powerful way to interact in real-time through WebSockets, offering a seamless experience for both developers and end users.
