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

# WebSocket

Represents a [WebSocket](/api-reference/voxengine/websocket) 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/websocket-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/websocket-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

<a id="onclose" />

Event handler to call when the connection is closed.

<a id="oncreated" />

Event handler to call when the connection is created.

<a id="onerror" />

Event handler to call when an error occurs.

<a id="onmediaended" />

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

<a id="onmediastarted" />

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

<a id="onmessage" />

Event handler to call when a message is received.

<a id="onopen" />

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

<a id="readystate" />

*readonly*

Returns the current state of the WebSocket connection.

<a id="url" />

*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.