Socket
注意
存在一个 API 更好且更标准的模块。
新的 k6/experimental/websockets API 部分实现了 WebSockets API 实时标准。
如有可能,我们建议使用新的 API。它使用全局事件循环以与其他 k6 API 保持一致并提供更好的性能。
Socket
是一个 WebSocket 客户端,用于与 WebSocket 连接进行交互。你可以使用它来监听 WebSocket 连接上发生的各种事件,并向服务器发送消息。此外,当 WebSocket 连接保持打开状态时,你可以使用 socket.setTimeout() 和 socket.setInterval() 在后台或重复执行代码。
方法 | 描述 |
---|---|
Socket.close() | 关闭 WebSocket 连接。 |
Socket.on(事件, 回调) | 在连接上设置事件监听器,监听以下任一事件 - 打开 (open) - 二进制消息 (binaryMessage) - 消息 (message) - ping - pong - 关闭 (close) - 错误 (error)。 |
Socket.ping() | 发送 ping。 |
Socket.send(数据) | 发送字符串数据。 |
Socket.sendBinary(数据) | 发送二进制数据。 |
Socket.setInterval(回调, 间隔) | 在连接打开时,以特定间隔重复调用函数。 |
Socket.setTimeout(回调, 周期) | 如果连接打开,延迟调用函数。 |
WebSocket 内置指标
k6
在通过 k6/ws
API 与 WebSocket 服务交互时会自动收集指标。请查阅指标参考中的列表。
查看结果输出文章,了解如何处理指标信息的更多信息。
示例
import ws from 'k6/ws';
import { check } from 'k6';
export default function () {
const url = 'ws://echo.websocket.org';
const params = { tags: { my_tag: 'hello' } };
const response = ws.connect(url, params, function (socket) {
socket.on('open', function open() {
console.log('connected');
socket.send(Date.now());
socket.setInterval(function timeout() {
socket.ping();
console.log('Pinging every 1sec (setInterval test)');
}, 1000);
});
socket.on('ping', function () {
console.log('PING!');
});
socket.on('pong', function () {
console.log('PONG!');
});
socket.on('pong', function () {
// Multiple event handlers on the same event
console.log('OTHER PONG!');
});
socket.on('message', function (message) {
console.log(`Received message: ${message}`);
});
socket.on('close', function () {
console.log('disconnected');
});
socket.on('error', function (e) {
if (e.error() != 'websocket: close sent') {
console.log('An unexpected error occured: ', e.error());
}
});
socket.setTimeout(function () {
console.log('2 seconds passed, closing the socket');
socket.close();
}, 2000);
});
check(response, { 'status is 101': (r) => r && r.status === 101 });
}
//VU execution won't be completely finished until the connection is closed.