UNPKG

you-yuan-uni-ui

Version:

you-yuan-uni-ui 组件库

178 lines (163 loc) 3.93 kB
/** * 定义一个socket对象 */ export class WebSocketObj { scoket = null; url = "wss://frame.yysoft.com.cn"; connectData = { sid: 1 }; constructor(url, data) { this.url = url this.connectData = data } getWebsocketUrl() { const queryList = [] if (Object.keys(this.connectData).length > 0) { for (const key in this.connectData) { queryList.push(key + "=" + this.connectData[key]) } } const fullUrl = this.url + "?" + queryList.join("&") console.log(fullUrl) return fullUrl } } /** * 定义一个socket消息对象 */ export class WebSocketMessageBody { SenderID = ""; ReceiverID = ""; MessageType = ""; Content = ""; constructor(ReceiverID, MessageType, Content) { this.ReceiverID = ReceiverID this.MessageType = MessageType this.Content = Content } toJSON() { return JSON.stringify({ SenderID: this.SenderID, ReceiverID: this.ReceiverID, MessageType: this.MessageType, Content: this.Content, }) } } export default { data() { return { websocketObj:{} } }, methods: { /** * 连接websocket */ websocketConnect(websocketObj) { const context = this // 先关闭,重新连接 context.websocketCloseSocket() websocketObj.socket = uni.connectSocket({ url: websocketObj.getWebsocketUrl(), // #ifdef MP-WEIXIN || APP-PLUS header: { 'content-type': 'application/json' }, // #endif // protocols: ['protocol1'], // #ifdef MP-WEIXIN method: 'GET', // #endif success(e) { console.log(e) // 连接成功 if (e.errMsg == "connectSocket:ok") { context.websocketOpen() context.websocketError() context.websocketObj = websocketObj } }, complete(e) { console.log(e) }, fail(e) { console.log(e) }, }); }, /** * 监听socket打开 */ websocketOpen(callback) { const context = this uni.onSocketOpen((res) => { console.log('WebSocket连接已打开!', res); callback && callback(res) context.websocketGetMessage() }); }, /** * 监听socket错误信息 */ websocketError(callback) { uni.onSocketError((res) => { console.log('WebSocket连接打开失败,请检查!', res); callback && callback(res) }); }, /** * 发送消息 */ websocketSendMessage(WebSocketMessageBody) { WebSocketMessageBody.SenderID = this.websocketObj.connectData.sid uni.sendSocketMessage({ data: WebSocketMessageBody.toJSON(), success(res) { console.log("消息发送成功", res) }, complete(res) {}, fail(err) { console.log("消息发送失败", err) }, }); }, /** * 接收消息 */ websocketGetMessage(callback) { uni.onSocketMessage((res) => { // console.log("收到消息", res) const data = JSON.parse(res.data) console.log("收到消息", data) callback && callback(data) }); }, /** * 关闭socket */ websocketCloseSocket() { uni.closeSocket({ code: 100, // 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭) reason: "我自己关闭了socket", // 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符) success(res) { console.log("WebSocket 关闭成功", res) }, complete(res) {}, fail(err) { console.log("WebSocket 关闭失败", err) }, }); }, /** * 监听socket关闭 */ websocketOnSocketClose(callback) { uni.onSocketClose((res) => { console.log('WebSocket 已关闭!', res); callback && callback(res) }); }, } }