菜单
开源

WebSocket.ping()

发送一个 ping。您可以使用 ping 消息来验证远程端点是否响应。

示例

一个 k6 脚本,它使用 onopen 处理器启动 WebSocket 连接,发送 ping,然后关闭连接。控制台应该打印 connection is alive,因为接收端应该自动发出 pong 事件。

JavaScript
import { WebSocket } from 'k6/experimental/websockets';

export default function () {
  const ws = new WebSocket('ws://:10000');

  ws.onopen = () => {
    console.log('WebSocket connection established!');
    ws.ping();
    ws.close();
  };

  ws.onpong = () => {
    // As required by the spec, when the ping is received, the recipient must send back a pong.
    console.log('connection is alive');
  };
}

前面的示例使用了 WebSocket 回显服务器,您可以使用以下命令运行它

bash
docker run --detach --rm --name ws-echo-server -p 10000:8080 jmalloc/echo-server