:::danger 该控件目前未全部完成 :::
/* eslint-disable no-undef */// eslint-disable-next-line @typescript-eslint/no-var-requiresconst websocket = require('websocket');// 控件类型定义const types = {type: 'SAMPLE_WEBSOCKET_WIDGET',icon: 'https://static.codemao.cn/appcraft/tmp-extension-widgets/test/websocket.svg',title: '长连接',platforms: ['android', 'ios'],properties: [{key: 'url',label: '链接',valueType: 'string',defaultValue: '',},{key: 'timeout',label: '超时毫秒数',valueType: 'number',defaultValue: 5000,},],methods: [{key: 'setHeader',label: '设置请求头',params: [{key: 'key',label: '请求头字段',valueType: 'string',defaultValue: '',},{key: 'value',label: '值',valueType: 'string',defaultValue: '',},],},{key: 'deleteHeader',label: '清除定时任务',params: [{key: 'key',label: '请求头字段',valueType: 'string',defaultValue: '',},],},{key: 'connect',label: '开始连接',params: [],},{key: 'send',label: '发送消息',params: [{key: 'msg',label: '',valueType: 'string',defaultValue: 'Hello',},],},{key: 'close',label: '中断连接',params: [],},],events: [{key: 'onConnect',label: '连接成功',params: [],},{key: 'onMessage',label: '收到消息',params: [{key: 'msg',label: '消息',valueType: 'string',},],},{key: 'onError',label: '发生错误',params: [{key: 'error',label: '错误信息文本',valueType: 'string',},],},],};// 控件实体定义class Widget extends InvisibleWidget {constructor(props) {super(props);this.url = props.url;this.timeout = props.timeout;this.headers = {};this.webSocketId = null;}setHeader(key, value) {console.log('setHeader', key, value);this.headers[key] = String(value);}deleteHeader(key) {if (Object.prototype.hasOwnProperty.call(this.headers, key)) {delete this.headers[key];}}connect() {console.log('connect');const options = {url: this.url,timeout: this.timeout,headers: this.headers,};websocket.wsConnect(options,(data) => {console.log('onConnect', data);this.webSocketId = data.webSocketId;this.emit('onConnect');},(data) => {console.log('onMessage', data);this.emit('onMessage', data.message);},() => {this.emit('onError');});}send(msg) {if (!this.webSocketId) {this.emit('onError', '连接未建立');return;}websocket.wsSend(this.webSocketId, msg);}close() {if (this.webSocketId) {websocket.wsClose(this.webSocketId);}}}exports.types = types;exports.widget = Widget;
