diff --git a/cim-use-examples/cim-client-wechat/README.txt b/cim-use-examples/cim-client-wechat/README.txt new file mode 100644 index 0000000..32f3d2f --- /dev/null +++ b/cim-use-examples/cim-client-wechat/README.txt @@ -0,0 +1,3 @@ +#微信小程序客户端代码示例 + +该示例使用json编解码策略,没有使用protobuf,所以服务端需要设置消息编码格式为json \ No newline at end of file diff --git a/cim-use-examples/cim-client-wechat/index.js b/cim-use-examples/cim-client-wechat/index.js new file mode 100644 index 0000000..d6d7224 --- /dev/null +++ b/cim-use-examples/cim-client-wechat/index.js @@ -0,0 +1,120 @@ + +const MESSAGE = 2; +const REPLY_BODY = 4; +const SENT_BODY = 3; +const PING = 1; +const PONG = 0; + +let self; + + Page({ + /** + * 页面的初始数据 + */ + data: { + websocketTask:undefined, + websocketConnected:false, + websocketConnectedTimes:0, + wssUri:"wss://your.doman.com", + + }, + + /** + * 生命周期函数--监听页面加载 + */ + onLoad(options) { + self = this; + this.createWebsocketConnection(); + }, + + + onShow() { + + }, + + sendWebsocketPong(){ + if(this.data.websocketTask == undefined){ + return; + } + + let pong = {}; + pong.type = PONG; + pong.content = 'PONG'; + + this.data.websocketTask.send({data:JSON.stringify(pong)}); + }, + + createWebsocketConnection(){ + + + let websocketTask = wx.connectSocket({url: this.data.wssUri,}); + + websocketTask.onOpen(function(res) { + + self.setData({websocketTask:websocketTask}); + + /** 链接成功发送bind请求*/ + let body = {}; + body.key = "client_bind"; + body.data = {}; + body.data.uid = '10000';//设置你的用户ID + body.data.channel = 'wechat'; + body.data.deviceId = '这里自己创建一个保存到本地的UUID'; + body.data.appVersion = '1.0.0'; + body.data.osVersion = wx.getSystemInfoSync().version; + body.data.deviceName = wx.getSystemInfoSync().platform; + + + let data = {}; + data.type = SENT_BODY; + data.content = JSON.stringify(body); + wx.sendSocketMessage({data:JSON.stringify(data)}); + }); + + websocketTask.onMessage(function(res) { + let message = JSON.parse(res.data); + let type = message.type; + if (type === PING) { + self.sendWebsocketPong(); + return; + } + + if (type === REPLY_BODY) { + //bind成功 + self.onWebsocketConnected(); + return; + } + + //拿到了后端发送的消息JSON + let content = JSON.parse(message.content); + + + }); + + + websocketTask.onClose(function(res) { + self.setData({websocketConnected:false}); + if(res.reason != 'FINISH'){ + // 在5秒后执行一次 + setTimeout(function(){ + self.createWebsocketConnection(self.data.room.id); + }, 5000); + } + }); + }, + + onWebsocketConnected(){ + + }, + + /** + * 生命周期函数--监听页面卸载 + */ + onUnload() { + let websocketTask = this.data.websocketTask; + if(websocketTask != null && websocketTask != undefined){ + websocketTask.close({code:1000,reason:"FINISH"}); + } + } + + }) \ No newline at end of file