Important: This documentation is about an older version. It's relevant only to the release noted, many of the features and functions have been updated or replaced. Please view the current version.

Open source RSS

Socket

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

Constructor

JavaScript
new Socket(options);

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

Parameters

ParameterTypeDescription
optionsobjectOptional socket configuration
options.tagsobjectCustom tags for metrics (key-value pairs). Applied to all metrics generated by this socket

Properties

PropertyTypeDescription
ready_stateSocketStateCurrent connection state: 'disconnected', 'opening', 'open', or 'destroyed'
connectedbooleanRead-only. true when ready_state is 'open'
local_ipstring | undefinedLocal IP address. Only available after the socket connects
local_portnumber | undefinedLocal port number. Only available after the socket connects
remote_ipstring | undefinedRemote IP address. Only available after the socket connects
remote_portnumber | undefinedRemote port number. Only available after the socket connects
bytes_writtennumberTotal bytes sent through this socket
bytes_readnumberTotal 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.

EventListener signatureDescription
connect() => voidEmitted when the connection is established
data(data: Uint8Array) => voidEmitted when data is received from the server
close() => voidEmitted when the connection is fully closed
error(error: Error) => voidEmitted on socket error
timeout() => voidEmitted when the inactivity timeout fires (see setTimeout())

Methods

MethodDescription
connect()Establish a TCP connection
write()Send data over the socket
destroy()Close and destroy the socket
setTimeout()Set inactivity timeout
on()Register an event handler

Example

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 = new TextDecoder().decode(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;
}