export default function() { ... }),直到压测结束。io.connect 方法阻塞,直到连接关闭。而在连接建立后的回调函数里(function (socket) {...}),会持续不断地监听和处理异步事件,直到压测结束。connect 方法建立连接,并在其回调函数里定义您的业务逻辑:protocol:协议类型,支持 polling(HTTP 长轮询)和 websocket(WebSocket)。headers:请求头参数。SocketIO对象传入回调函数。您可在回调函数里,定义您的 Socket.IO 请求逻辑,发送/收取事件消息。connect 会返回 Response 对象,200 为成功返回码。SocketIO 对象的常用方法:emit:发送事件。参数为事件名、消息数据、回调函数:event:自定义事件的名称。msg:文本消息或二进制数据。callback: (可选)回调函数。close:关闭连接。on:监听事件,并用回调函数处理事件。PTS 支持监听的事件列表如下:事件名 | 事件用途 |
open | 建立连接 |
close | 关闭连接 |
error | 发生错误 |
message | 接收文本消息 |
binaryMessage | 接收二进制消息 |
setTimeout: 等待 intervalMs 毫秒后执行函数。setInterval:按照 intervalMs 毫秒定期执行函数。setLoop:循环执行函数直至 context 结束或者连接关闭。// SocketIO APIimport socketio from 'pts/socketio';import { check, sleep } from 'pts';import util from 'pts/util';export default function () {const res = socketio.connect('http://localhost:8080', function (socket) {socket.on('open', () => console.log('connected'));socket.on('message', (data) => console.log('message received: ', data));socket.on('binaryMessage', (data) => console.log('binaryMessage received: ', data));socket.on('close', () => console.log('disconnected'));socket.setTimeout(function () {console.log('3 seconds passed, closing the socket');socket.close();}, 3000);// 设置定时任务socket.setTimeout(function () {socket.emit('message', 'hello');socket.emit('binaryMessage', util.base64Decoding('aGVsbG8=', 'std', 'b'));socket.emit('ackMessage', 'hello ack', function(msg) {console.log('ack message received: ', msg)})}, 500);// 设置定期执行的任务socket.setInterval(function(){socket.emit('message', 'interval message');}, 500);// 设置循环执行任务,socket/context 关闭自然退出socket.setLoop(function () {sleep(0.1);socket.emit('message', 'loop message');});}, {// 支持 polling、websocket 协议protocol:'websocket',headers: {token: 'xxx',}});check('status is 200', () => res.status === 200);}
文档反馈