Blogger Information
Blog 67
fans 0
comment 2
visits 71824
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
微信小程序wx.connectSocket长链接示例
搁浅
Original
446 people have browsed it

连上后,退出时一定要关闭链接,如果不关闭,就算是点击的同一个用户聊天,也会重新打开一个链接,最多打开5个长链接。

  1. var SocketTask
  2. Page({
  3. /**
  4. * 页面的初始数据
  5. */
  6. data: {
  7. topLabel: '',
  8. iploads: app.iploads,
  9. inputlg: 0,
  10. message: '',//消息内容
  11. toUser:'',//接收用户id
  12. socketStatus:false,//有没有打开webSocket链接
  13. xtyhbh:'',//医生聊天BH
  14. },
  15. bindmsg(e) {//输入文字不大于300
  16. if (e.detail.value.length <= 300) {
  17. this.setData({
  18. message: e.detail.value,
  19. inputlg: e.detail.value.length
  20. })
  21. }
  22. },
  23. openSocket() {//监听状态
  24. SocketTask.onOpen(() => {
  25. // console.log('WebSocket 已连接')
  26. this.setData({socketStatus:true})
  27. })
  28. SocketTask.onClose(() => {
  29. // console.log('WebSocket 已断开')
  30. this.setData({socketStatus:false})
  31. })
  32. SocketTask.onError(error => {
  33. // console.error('发生错误', JSON.stringify(error))
  34. // this.setData({
  35. // loading: false
  36. // })
  37. })
  38. // 监听服务器推送消息
  39. SocketTask.onMessage(message => {
  40. // console.log('收到服务器信道消息');
  41. message.data=JSON.parse(message.data)
  42. console.log('socket message:', message.data)
  43. let chatList=[]
  44. switch (Number(message.data.type)) {
  45. case 9:
  46. chatList=this.data.chatList
  47. chatList.push({
  48. egp: 1,
  49. isSelf: true,
  50. content: this.data.message,
  51. imgSrc: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big143004.jpg',
  52. time: message.data.formDate
  53. })
  54. this.setData({chatList,message:'',inputlg:0})
  55. break;
  56. case 3:
  57. chatList=this.data.chatList
  58. chatList.push({
  59. egp: 1,
  60. isSelf: false,
  61. content: message.data.message,
  62. imgSrc: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big143004.jpg',
  63. time: message.data.formDate
  64. })
  65. this.setData({chatList})
  66. break;
  67. }
  68. })
  69. },
  70. openSocket() {//第二种监听写法
  71. wx.onSocketOpen(() => {
  72. // console.log('WebSocket 已连接')
  73. this.setData({socketStatus:true})
  74. })
  75. wx.onSocketClose(() => {
  76. // console.log('WebSocket 已断开')
  77. this.setData({socketStatus:false})
  78. })
  79. wx.onSocketError(error => {
  80. console.error('发生错误', JSON.stringify(error))
  81. // this.setData({
  82. // loading: false
  83. // })
  84. })
  85. // 监听服务器推送消息
  86. wx.onSocketMessage(message => {
  87. // console.log('收到服务器信道消息');
  88. message.data=JSON.parse(message.data)
  89. console.log('socket message:', message.data)
  90. let chatList=[]
  91. switch (Number(message.data.type)) {
  92. case 9:
  93. chatList=this.data.chatList
  94. chatList.push({
  95. egp: 1,
  96. isSelf: true,
  97. content: this.data.message,
  98. imgSrc: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big143004.jpg',
  99. time: message.data.formDate
  100. })
  101. this.setData({chatList,message:'',inputlg:0})
  102. break;
  103. case 3:
  104. chatList=this.data.chatList
  105. chatList.push({
  106. egp: 1,
  107. isSelf: false,
  108. content: message.data.message,
  109. imgSrc: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big143004.jpg',
  110. time: message.data.formDate
  111. })
  112. this.setData({chatList})
  113. break;
  114. }
  115. })
  116. },
  117. webSocket(){//长链接请求
  118. SocketTask=wx.connectSocket({
  119. url: 'http://192.168.3.5'+'?token=55555555555555555555555ss',
  120. })
  121. // SocketTask.onOpen((result) => {console.log('onOpen: true',result)})
  122. // SocketTask.onMessage((result) => {console.log('onMessage: true',result)})//服务器返回的消息
  123. this.openSocket()
  124. },
  125. sendSocketMessage() {//发送消息
  126. if(this.data.socketStatus){
  127. if(this.data.message){
  128. let data={
  129. type:3,
  130. toUser:this.data.xtyhbh,//发送给谁
  131. // formUser:'',//谁发送的
  132. message:this.data.message,//发送的消息
  133. sendNo:this.uuid2()}//每条消息ID
  134. SocketTask.send({data: JSON.stringify(data)})
  135. }else{
  136. Toast.fail('消息不能为空');
  137. }
  138. }else{
  139. Toast.fail('发送失败,未连接上服务器');
  140. }
  141. },
  142. chat() {//滚动到底部
  143. this.setData({
  144. chat: this.data.chatList.length-1,
  145. })
  146. },
  147. uuid2() {//uuid2随机数32位
  148. var s = [];
  149. var hexDigits = "0123456789abcdef";
  150. for (var i = 0; i < 32; i++) {
  151. s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  152. }
  153. s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  154. s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  155. s[8] = s[13] = s[18] = s[23];
  156. var uuid = s.join("");
  157. return uuid;
  158. },
  159. /**
  160. * 生命周期函数--监听页面加载
  161. */
  162. onLoad: function (options) {
  163. this.setData({
  164. bh: options.bh,
  165. topLabel: options.xm
  166. })
  167. this.webSocket()
  168. },
  169. /**
  170. * 生命周期函数--监听页面初次渲染完成
  171. */
  172. onReady: function () {
  173. },
  174. /**
  175. * 生命周期函数--监听页面显示
  176. */
  177. onShow: function () {
  178. },
  179. /**
  180. * 生命周期函数--监听页面隐藏
  181. */
  182. onHide: function () {
  183. SocketTask.close()//关闭webSocket链接
  184. },
  185. /**
  186. * 生命周期函数--监听页面卸载
  187. */
  188. onUnload: function () {
  189. SocketTask.close()//关闭webSocket链接
  190. },
  191. /**
  192. * 页面相关事件处理函数--监听用户下拉动作
  193. */
  194. onPullDownRefresh: function () {
  195. },
  196. /**
  197. * 页面上拉触底事件的处理函数
  198. */
  199. onReachBottom: function () {
  200. },
  201. /**
  202. * 用户点击右上角分享
  203. */
  204. onShareAppMessage: function () {
  205. }
  206. })

定位到底部最后一条信息

  1. <scroll-view scroll-into-view="chat{{chat}}">
  2. <view class="cu-chat" id="chat{{index}}" wx:for="{{chatList}}" wx:key="index" wx:for-item="chatitem">
  3. </view>
  4. </scroll-view>
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post