---
title: "Socket | Grafana k6 documentation"
description: "TCP socket for connecting to servers and managing data transfer"
---

# Socket

The `Socket` class provides an event-driven interface for establishing TCP connections, sending and receiving data, and managing the connection lifecycle.

## Constructor

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

```javascript
new Socket(options)
```

Creates a new TCP socket in the `disconnected` state. Use `connect()` to establish a connection.

### Parameters

Expand table

| Parameter    | Type   | Description                                                                                |
|--------------|--------|--------------------------------------------------------------------------------------------|
| options      | object | Optional socket configuration                                                              |
| options.tags | object | Custom tags for metrics (key-value pairs). Applied to all metrics generated by this socket |

## Properties

Expand table

| Property        | Type          | Description                                                                         |
|-----------------|---------------|-------------------------------------------------------------------------------------|
| `ready_state`   | `SocketState` | Current connection state: `'disconnected'`, `'opening'`, `'open'`, or `'destroyed'` |
| `connected`     | boolean       | Read-only. `true` when `ready_state` is `'open'`                                    |
| `local_ip`      | string        | undefined                                                                           |
| `local_port`    | number        | undefined                                                                           |
| `remote_ip`     | string        | undefined                                                                           |
| `remote_port`   | number        | undefined                                                                           |
| `bytes_written` | number        | Total bytes sent through this socket                                                |
| `bytes_read`    | number        | Total bytes received through this socket                                            |

## Events

Register handlers for these events using `socket.on()`. The socket supports only one listener per event. Registering a second listener replaces the first.

Expand table

| Event     | Listener signature           | Description                                                    |
|-----------|------------------------------|----------------------------------------------------------------|
| `connect` | `() => void`                 | Emitted when the connection is established                     |
| `data`    | `(data: Uint8Array) => void` | Emitted when data is received from the server                  |
| `close`   | `() => void`                 | Emitted when the connection is fully closed                    |
| `error`   | `(error: Error) => void`     | Emitted on socket error                                        |
| `timeout` | `() => void`                 | Emitted when the inactivity timeout fires (see `setTimeout()`) |

## Methods

Expand table

| Method                                                                      | Description                  |
|-----------------------------------------------------------------------------|------------------------------|
| [connect()](/docs/k6/latest/javascript-api/k6-x-tcp/socket/connect/)        | Establish a TCP connection   |
| [write()](/docs/k6/latest/javascript-api/k6-x-tcp/socket/write/)            | Send data over the socket    |
| [destroy()](/docs/k6/latest/javascript-api/k6-x-tcp/socket/destroy/)        | Close and destroy the socket |
| [setTimeout()](/docs/k6/latest/javascript-api/k6-x-tcp/socket/set-timeout/) | Set inactivity timeout       |
| [on()](/docs/k6/latest/javascript-api/k6-x-tcp/socket/on/)                  | Register an event handler    |

## Example

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

```javascript
import { Socket } from "k6/x/tcp"

export default async function () {
  const socket = new Socket({ tags: { service: "echo" } })

  const closed = new Promise((resolve) => {
    socket.on("close", () => {
      console.log("Connection closed")
      resolve()
    })
  })

  socket.on("data", (data) => {
    const str = String.fromCharCode.apply(null, new Uint8Array(data))
    console.log("Received:", str)
    socket.destroy()
  })

  socket.on("error", (err) => {
    console.error("Error:", err)
  })

  const host = __ENV.TCP_HOST || "localhost"
  const port = __ENV.TCP_PORT || "8080"

  await socket.connect(port, host)
  console.log("Connected. State:", socket.ready_state)
  await socket.write("Hello, server!")

  await closed
}
```
