xk6-tcp
    Preparing search index...

    Class Socket

    TCP Socket implementation for k6 performance testing.

    Provides a Node.js-compatible API for TCP socket operations, adapted for the k6 environment. Supports both synchronous and asynchronous operations with comprehensive event handling.

    import { Socket } from 'k6/x/tcp';

    const socket = new Socket();

    socket.on('connect', () => {
    console.log('Connected to server');
    socket.write('Hello, World!', {
    tags: { message_type: 'greeting' }
    });
    });

    socket.on('data', (data) => {
    console.log('Received:', String.fromCharCode.apply(null, new Uint8Array(data)));
    });

    socket.connect(8080, 'example.com');
    Index

    Constructors

    • Creates a new TCP socket instance.

      The socket is created in a disconnected state. Use connect() to establish a connection.

      Parameters

      • Optionaloptions: SocketOptions

        Optional configuration for the socket

      Returns Socket

      // Create a basic socket
      const socket = new Socket();

      // Create a socket with tags for metrics
      const taggedSocket = new Socket({
      tags: { component: 'api-client', version: '1.0' }
      });

    Properties

    bytes_read: number

    Total number of bytes received through this socket.

    Increments with each 'data' event. Useful for tracking received data volumes and bandwidth usage.

    socket.on('data', (data) => {
    console.log(`Received ${data.byteLength} bytes (${socket.bytes_read} total)`);
    });
    bytes_written: number

    Total number of bytes successfully sent through this socket.

    Increments with each write() operation. Useful for tracking data transfer volumes in metrics and debugging.

    socket.write('Hello');
    console.log(`Sent ${socket.bytes_written} bytes total`);
    connected: boolean

    Indicates whether the socket is currently connected to a remote endpoint.

    This is a convenience property that returns true when ready_state is 'open', and false otherwise. It provides a simple boolean check for connection status.

    if (socket.connected) {
    socket.write('Hello!');
    } else {
    console.log('Socket not connected');
    }
    local_ip?: string

    The local IP address used for this connection.

    Available after the socket is connected. Useful for debugging network routing or when testing from hosts with multiple interfaces.

    socket.on('connect', () => {
    console.log(`Connected from ${socket.local_ip}:${socket.local_port}`);
    });
    local_port?: number

    The local port number used for this connection.

    Available after the socket is connected. The OS typically assigns an ephemeral port from the available port range.

    ready_state: SocketState

    The current state of the socket connection.

    Provides detailed information about the socket's lifecycle state, similar to Node.js net.Socket readyState.

    Read this property to check the connection status before performing operations or for debugging connection issues.

    console.log('Socket state:', socket.ready_state);
    // Output: 'disconnected', 'opening', 'open', or 'destroyed'

    // Check before writing
    if (socket.ready_state === 'open') {
    socket.write('Hello!');
    }
    remote_ip?: string

    The remote IP address of the connected server.

    Available after DNS resolution completes during connection. This shows the actual IP address even if you connected using a hostname.

    remote_port?: number

    The remote port number of the connected server.

    This is the port you specified in the connect() call.

    Methods

    • Initiates a TCP connection to the specified host and port.

      This method is non-blocking and returns immediately. Listen for the 'connect' event to know when the connection is established, or 'error' for failures.

      Parameters

      • port: number

        The destination port number (1-65535)

      • Optionalhost: string

        The destination hostname or IP address (defaults to 'localhost')

      Returns this

      The socket instance for method chaining

      socket.on('connect', () => console.log('Connected!'));
      socket.on('error', (err) => console.error('Connection failed:', err));
      socket.connect(8080, 'api.example.com');
    • Initiates a TCP connection using detailed connection options.

      This method is non-blocking and returns immediately. Listen for the 'connect' event to know when the connection is established, or 'error' for failures.

      Parameters

      Returns this

      The socket instance for method chaining

      socket.on('connect', () => console.log('Connected!'));
      socket.connect({
      port: 8080,
      host: 'api.example.com',
      tags: { endpoint: 'api-server' }
      });
    • Asynchronously establishes a TCP connection to the specified host and port.

      Returns a Promise that resolves when the connection is established, or rejects on connection failure. This is useful for sequential operations where you need to ensure the connection is ready before proceeding.

      Parameters

      • port: number

        The destination port number (1-65535)

      • Optionalhost: string

        The destination hostname or IP address. Defaults to 'localhost'

      Returns Promise<void>

      A Promise that resolves when connected successfully

      try {
      await socket.connectAsync(8080, 'example.com');
      console.log('Connected to server');
      await socket.writeAsync('Hello!');
      } catch (error) {
      console.error('Connection failed:', error);
      }
    • Asynchronously establishes a TCP connection using detailed options.

      Returns a Promise that resolves when the connection is established, or rejects on connection failure. Useful for async/await workflows.

      Parameters

      • options: ConnectOptions

        Connection options including port, host, TLS, and tags

      Returns Promise<void>

      A Promise that resolves when connected successfully

      // Connect with TLS
      await socket.connectAsync({
      port: 443,
      host: 'secure.example.com',
      tls: true,
      tags: { protocol: 'https' }
      });
      console.log('Secure connection established');
    • Destroys the socket and closes the connection.

      Once destroyed, the socket cannot be reused. All pending operations will be terminated and a 'close' event will be emitted.

      If an error is provided, an 'error' event will be emitted before closing.

      Parameters

      • Optionalerror: Error

        Optional error to emit before closing the socket

      Returns this

      The socket itself for method chaining

      // Clean shutdown
      socket.destroy();

      // Destroy with error
      socket.destroy(new Error('Connection timeout'));

      // Common pattern: destroy after data received
      socket.on('data', (data) => {
      processData(data);
      socket.destroy();
      });
    • Registers an event listener for the 'connect' event.

      The 'connect' event is emitted when the socket successfully establishes a connection to the remote server. This indicates the socket is ready for reading and writing data.

      Important: Only one listener is supported per event type. Calling this method multiple times will replace the previously set listener.

      Parameters

      • event: "connect"

        The event name 'connect'

      • listener: () => void

        Callback function invoked when the connection is established

      Returns this

      The socket instance for method chaining

      socket.on('connect', () => {
      console.log('Connected! Ready to send data.');
      socket.write('Hello, server!');
      });
    • Registers an event listener for the 'data' event.

      The 'data' event is emitted when data is received from the remote endpoint. The data is provided as an ArrayBuffer for efficient binary data handling.

      Important: Only one listener is supported per event type. Calling this method multiple times will replace the previously set listener.

      Parameters

      • event: "data"

        The event name 'data'

      • listener: (data: ArrayBuffer) => void

        Callback function invoked when data is received

      Returns this

      The socket instance for method chaining

      socket.on('data', (data) => {
      const text = String.fromCharCode.apply(null, new Uint8Array(data));
      console.log('Received:', text);

      // Or handle binary data directly
      const bytes = new Uint8Array(data);
      console.log('Binary data:', bytes);
      });
    • Registers an event listener for the 'close' event.

      The 'close' event is emitted when the socket connection is fully closed by either the local or remote endpoint. This is the final event in the socket lifecycle.

      This event is guaranteed to be emitted exactly once per socket, making it ideal for cleanup operations and resolving promises in async patterns.

      Important: Only one listener is supported per event type. Calling this method multiple times will replace the previously set listener.

      Parameters

      • event: "close"

        The event name 'close'

      • listener: () => void

        Callback function invoked when the socket closes

      Returns this

      The socket instance for method chaining

      // Basic usage
      socket.on('close', () => {
      console.log('Connection closed');
      });

      // Async pattern with Promise
      const closePromise = new Promise((resolve) => {
      socket.on('close', resolve);
      });

      socket.connect(8080, 'example.com');
      await closePromise; // Wait for connection to close
    • Registers an event listener for the 'error' event.

      The 'error' event is emitted when a socket error occurs, such as connection failures, network issues, or protocol errors. It's crucial to handle this event to prevent unhandled errors.

      Important: Only one listener is supported per event type. Calling this method multiple times will replace the previously set listener.

      Parameters

      • event: "error"

        The event name 'error'

      • listener: (error: Error) => void

        Callback function invoked when an error occurs, receives the Error object

      Returns this

      The socket instance for method chaining

      socket.on('error', (error) => {
      console.error('Connection failed:', error.message);
      // Handle the error appropriately
      socket.destroy();
      });
    • Registers an event listener for the 'timeout' event.

      The 'timeout' event is emitted when the socket times out due to inactivity as configured by setTimeout(). Note that the socket is not automatically destroyed after a timeout - you must manually call destroy() if needed.

      Important: Only one listener is supported per event type. Calling this method multiple times will replace the previously set listener.

      Parameters

      • event: "timeout"

        The event name 'timeout'

      • listener: () => void

        Callback function invoked when the socket times out

      Returns this

      The socket instance for method chaining

      socket.setTimeout(30000); // Set 30-second timeout
      socket.on('timeout', () => {
      console.log('Connection timed out after 30 seconds');
      socket.destroy(); // Manually close the socket
      });
    • Sets the socket timeout for inactivity.

      Sets the socket to timeout after timeout milliseconds of inactivity on the socket. By default, TCP sockets do not have a timeout. When an idle timeout is triggered, the socket will receive a 'timeout' event but the connection will not be severed. The user must manually call destroy() to end the connection.

      If timeout is 0, then the existing idle timeout is disabled.

      Parameters

      • timeout: number

        Timeout duration in milliseconds. Use 0 to disable timeout

      Returns this

      The socket instance for method chaining

      // Set a 30-second timeout
      socket.setTimeout(30000);
      socket.on('timeout', () => {
      console.log('Socket timed out');
      socket.destroy();
      });

      // Disable timeout
      socket.setTimeout(0);
    • Sends data on the socket with additional options.

      Parameters

      • data: string | ArrayBuffer

        The data to write - can be a string or ArrayBuffer for binary data

      • Optionaloptions: WriteOptions

        Optional configuration options for the write operation

      Returns boolean

      true if the data was flushed successfully

      // Write with encoding
      socket.write('SGVsbG8gV29ybGQ=', { encoding: 'base64' });

      // Write with tags for metrics
      socket.write('Hello, server!', {
      tags: { operation: 'handshake', protocol: 'custom' }
      });

      // Write with both encoding and tags
      socket.write('encoded-payload', {
      encoding: 'hex',
      tags: { data_type: 'binary', size: 'small' }
      });
    • Asynchronously sends data on the socket with additional options. Returns a Promise that resolves when the data has been written to the socket.

      Parameters

      • data: string | ArrayBuffer

        The data to write - can be a string or ArrayBuffer for binary data

      • Optionaloptions: WriteOptions

        Optional configuration options for the write operation

      Returns Promise<void>

      A Promise that resolves when the data has been successfully written

      // Write with encoding
      await socket.writeAsync('SGVsbG8gV29ybGQ=', { encoding: 'base64' });

      // Write with tags for metrics
      await socket.writeAsync('Hello, server!', {
      tags: { operation: 'handshake', protocol: 'custom' }
      });

      // Write with both encoding and tags
      await socket.writeAsync('encoded-payload', {
      encoding: 'hex',
      tags: { data_type: 'binary', size: 'small' }
      });