JavaScript API 中的 pts/socketio 模块实现了 socketio 相关的功能。
方法
方法 | 返回类型 | 描述 |
建立 Socket.IO 连接,并在回调函数中定义业务逻辑,执行完回调函数后,返回 Response 对象。 |
对象
样例
// 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);}