# Connection Class

## Content

`Connection` is an object returned by the [connect ](/spreadjs/api/v18/collaboration/js-collaboration-client/classes/Client#connect)method of the [Client ](/spreadjs/api/v18/collaboration/js-collaboration-client/classes/Client)class, representing a bidirectional connection with the server. This guide will teach you to:

* Send and receive messages
* Listen for events
* Manage connections

## Properties

### id

Each new connection is assigned a random 20-character identifier.
This identifier is synchronized with the server-side value.

>type=note
> This ID is regenerated each time a reconnection occurs.

```typescript
// Client-side
connection.on("connect", () => {
    console.log(connection.id); // Example output: XBtqzsRMPh7MaVvaAAAB
});
connection.on("disconnect", () => {
    console.log(connection.id); // undefined
});
```

```typescript
// Server-side
server.on("connect", ({ connection }) => {
    console.log(connection.id); // Example output: XBtqzsRMPh7MaVvaAAAB
});
```

### roomId

The ID of the room to which the connection belongs.

```typescript
console.log('connection.roomId'); // Example output: "room1"
```

### connected

Indicates whether the connection is currently connected to the server.

```typescript
connection.on("connect", () => {
    console.log(connection.connected); // true
});
connection.on("disconnect", () => {
    console.log(connection.connected); // false
});
```

## Lifecycle

![connection_class-lifecycle](https://cdn.mescius.io/document-site-files/images/7719ad0a-f083-46d7-aff6-f63e2e187c15/connection_class-lifecycle.6b0f22.png?width=500&verticalAlign=middle)

## Methods

### send

Use the `send` method to send messages to the server.

```typescript
connection.send('Hello, server!');
connection.send('Hello, server!', 'document');
connection.send({ userId: 'user1', active: true });
connection.send({ userId: 'user1', active: true }, 'my-presence');
```

**Parameters**

* `data`: The data to be sent.
* `type` (optional): The message type, used to identify the purpose or category of the message.

**Example**

```javascript
// Send a document update
connection.send({ content: 'New paragraph' }, 'my-document');
// Send an online status
connection.send({ userId: 'user1', active: true }, 'my-presence');
// Receive and distinguish messages
connection.on('message', (data, type) => {
    if (type === 'my-document') {
        console.log('Document update:', data);
    } else if (type === 'my-presence') {
        console.log('Status update:', data);
    }
});
```

### close

Use the `close` method to close the connection.

```javascript
connection.close();
```

### on

Add an event listener.

```javascript
connection.on('connect', () => {
    console.log('Connected to the server');
});
connection.on('message', (data, type) => {
    console.log('Received message:', data, 'Type:', type);
});
```

### once

Add a one-time listener that is automatically removed after being triggered.

```javascript
connection.once('reconnect', (attempts) => {
    console.log(`Reconnection attempt #${attempts}`);
});
```

### off

Remove an event listener.

```javascript
const handler = () => console.log('Error occurred');
connection.on('error', handler);
connection.off('error', handler);
```

## Events

#### Supported Events

| Event Name | Description | Parameters |
| ---------- | ----------- | ---------- |
| `connect` | Triggered when the connection is established | None |
| `message` | Triggered when a message is received | `data` (message content), `type` (message type) |
| `disconnect` | Triggered when the connection is disconnected | `reason` (disconnection reasons will be detailed in the table below) |
| `error` | Triggered when an error occurs | `error` (error object) |
| `reconnectAttempts` | Triggered during reconnection attempts | `attempts` (number of attempts) |
| `reconnect` | Triggered when reconnection is successful | `attempts` (number of retries) |
| `reconnectFailed` | Triggered when reconnection fails | None |

#### Disconnection Reasons

The following table lists the disconnection reasons of the `disconnect` event.

| Value | Description |
| ----- | ----------- |
| `CLIENT_DISCONNECT` | Client actively disconnected |
| `SERVER_DISCONNECT` | Server actively disconnected |
| `PING_TIMEOUT` | Client failed to respond to ping in time |
| `TRANSPORT_CLOSE` | Transport layer connection closed |
| `TRANSPORT_ERROR` | Transport layer error occurred |
