This is documentation for the next version of Grafana k6 documentation. For the latest stable release, go to the latest version.

Open source

Socket.destroy()

Closes the connection and destroys the socket. After you call destroy(), the socket transitions to the 'destroyed' state, and you can’t reuse it. A close event is emitted after the socket is destroyed.

Signature

JavaScript
socket.destroy()

Parameters

None.

Returns

void

Example

JavaScript
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("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)
    socket.destroy()
  })

  await socket.connect(8080, "example.com")
  await socket.write("Hello, server!")

  await closed
}