Socket.setTimeout(callback, delay)
注意
存在一个更好且符合标准的模块 API。
新的 k6/experimental/websockets API 部分实现了 WebSockets API living standard。
如果可能,我们推荐使用新的 API。它使用全局事件循环,与其他 k6 API 保持一致并提供更好的性能。
如果在延迟时间到达时 WebSocket 连接仍处于打开状态,则调用一个函数。
参数 | 类型 | 描述 |
---|---|---|
callback | function | 当 delay 时间到期时要调用的函数。 |
delay | number | 延迟时间,单位为毫秒。 |
示例
import ws from 'k6/ws';
import { sleep } from 'k6';
export default function () {
console.log('T0: Script started');
const url = 'ws://echo.websocket.org';
const response = ws.connect(url, null, function (socket) {
console.log('T0: Entered WebSockets run loop');
socket.setTimeout(function () {
console.log('T0+1: This is printed');
}, 1000);
socket.setTimeout(function () {
console.log('T0+2: Closing socket');
socket.close();
}, 2000);
socket.setTimeout(function () {
console.log('T0+3: This is not printed, because socket is closed');
}, 3000);
});
console.log('T0+2: Exited WebSockets run loop');
sleep(2);
console.log('T0+4: Script finished');
}