---
title: "WebSocket | Grafana k6 documentation"
description: "Create a WebSocket connection, and provides a WebSocket instance to interact with the service."
---

> For a curated documentation index, see [llms.txt](/llms.txt). For the complete documentation index, see [llms-full.txt](/llms-full.txt).

# WebSocket

Creates a WebSocket instance for connection to a remote host.

The following events can close the connection:

- remote host close event.
- [WebSocket.close()](/docs/k6/next/javascript-api/k6-websockets/websocket/websocket-close/).
- k6 VU interruption based on test configuration or CLI commands.

Expand table

| Parameter | Type   | Description                                                                                                   |
|-----------|--------|---------------------------------------------------------------------------------------------------------------|
| url       | string | The URL to which to connect (e.g. “ws://localhost:10000”).                                                    |
| protocols | array  | Not yet implemented, reserved for the future use.                                                             |
| params    | object | [Params](/docs/k6/next/javascript-api/k6-websockets/params/) object containing additional request parameters. |

### Returns

Expand table

| Type      | Description                      |
|-----------|----------------------------------|
| WebSocket | An instance of WebSocket object. |

### Example

*A k6 script that initiates a WebSocket connection.*

JavaScript ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```javascript
import { WebSocket } from 'k6/websockets';

export default function () {
  const ws = new WebSocket('ws://localhost:10000');

  ws.onopen = () => {
    console.log('WebSocket connection established!');
    ws.close();
  };
}
```

The preceding example uses a WebSocket echo server, which you can run with the following command:

Bash ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```bash
docker run --detach --rm --name ws-echo-server -p 10000:8080 jmalloc/echo-server
```
