> For a complete documentation index, fetch https://docs.voximplant.ai/llms.txt

# WebSocket

Represents a [WebSocket](/api-reference/voxengine/web-socket) instance that provides the API for creating and managing an outgoing or incoming WebSocket connection, as well as for sending and receiving data to/from it.

## Constructor

```ts
new WebSocket(url: string, parameters?: WebSocketParameters)
```

**Parameters**

```ts
new WebSocket(url: string, parameters?: WebSocketParameters)
```

**Parameters**

## Methods

### addEventListener

Adds a handler for the specified [WebSocketEvents](/api-reference/voxengine/web-socket-events) event. Use only functions as handlers; anything except a function leads to the error and scenario termination when a handler is called.

```ts
addEventListener(event: WebSocketEvents | T, callback: (event: _WebSocketEvents[T]) => any): void
```

**Parameters**

### clearMediaBuffer

Clears the media buffer.

```ts
clearMediaBuffer(parameters?: ClearMediaBufferParameters): void
```

**Parameters**

### close

Closes the WebSocket connection or connection attempt.

```ts
close(): void
```

### id

Returns the WebSocket's id.

```ts
id(): string
```

### removeEventListener

Removes a handler for the specified [WebSocketEvents](/api-reference/voxengine/web-socket-events) event.

```ts
removeEventListener(event: WebSocketEvents | T, callback?: (event: _WebSocketEvents[T]) => any): void
```

**Parameters**

### send

Enqueues the specified data to be transmitted over the WebSocket connection.

```ts
send(data: string): void
```

**Parameters**

### sendMediaTo

Starts sending media from the websocket to the media unit. WebSocket works in real time and the recommended duration of one audio chunk is **20** milliseconds.

```ts
sendMediaTo(mediaUnit: VoxMediaUnit, parameters?: SendMediaParameters): void
```

**Parameters**

### stopMediaTo

Stops sending media from the websocket to the media unit.

```ts
stopMediaTo(mediaUnit: VoxMediaUnit, parameters?: SendMediaParameters): void
```

**Parameters**

## Properties

Event handler to call when the connection is closed.

Event handler to call when the connection is created.

Event handler to call when an error occurs.

Event handler to call after the end of the audio stream.

Event handler to call when the audio stream is started playing.

Event handler to call when a message is received.

Event handler to call when the connection is open (ready to send and receive data).

*readonly*

Returns the current state of the WebSocket connection.

*readonly*

Returns the absolute URL of the WebSocket. For outgoing connection, it is the URL to which to connect; for incoming, it is the WebSocket session URL.