This is documentation for the next version of Grafana k6 documentation. For the latest stable release, go to the latest version.
Socket.on()
Registers an event listener for a socket lifecycle event. All event handlers execute in the context of the k6 VU event loop.
Only one listener per event type is supported. Calling on() for an event that already has a listener replaces the previous one.
Signature
socket.on(event, listener)Parameters
| Parameter | Type | Description |
|---|---|---|
| event | string | Event name: 'connect', 'data', 'close', 'error', or 'timeout' |
| listener | function | Callback invoked when the event fires |
Events
connect
Emitted when the socket successfully establishes a connection to the remote server.
Signature
socket.on("connect", () => {
// Connection established
})data
Emitted when data is received from the remote endpoint. The data is provided as a Uint8Array.
Signature
socket.on("data", (data) => {
// data is Uint8Array
})Parameters
| Parameter | Type | Description |
|---|---|---|
| data | Uint8Array | The received data |
close
Emitted when the socket connection is fully closed, either by the local or remote side. This is the final event in the socket lifecycle and is emitted exactly once per socket.
Signature
socket.on("close", () => {
// Connection fully closed
})error
Emitted when a socket error occurs, such as a connection failure or network issue.
Signature
socket.on("error", (error) => {
// Handle error
})Parameters
| Parameter | Type | Description |
|---|---|---|
| error | Error | The error object |
timeout
Emitted when the socket times out due to inactivity as configured by setTimeout(). The socket doesn’t automatically close the connection—call destroy() to close it.
Signature
socket.on("timeout", () => {
// Inactivity timeout reached
})Returns
void
Example
import { Socket } from "k6/x/tcp"
export default async function () {
const socket = new Socket()
const closed = new Promise((resolve) => {
socket.on("close", () => {
console.log("Connection closed")
resolve()
})
})
socket.on("connect", () => {
console.log("Connected to server")
})
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("Socket error:", err)
socket.destroy()
})
socket.on("timeout", () => {
console.log("Socket timed out")
socket.destroy()
})
await socket.connect(8080, "example.com")
await socket.write("Hello, server!")
await closed
}Was this page helpful?
Related resources from Grafana Labs

