使用Websocket技术实现聊天功能--小程序前端部分(一)

1 篇文章 0 订阅
1 篇文章 0 订阅

功能架构图


Config.js代码

class Config {
  constructor() {

  }
}


// 本地地址
Config.requestUrl = "http://localhost:8090/MiniProgram/"
// websocket的请求协议是ws,部署到服务其上之后需要更改为wss
Config.webSocketUrl = "ws://localhost:8080/WebSocket/"

// 云服务器地址
//Config.requestUrl = "https://服务器域名/MiniProgram/"
// websocket的请求协议是ws,部署到服务其上之后需要更改为wss
//Config.webSocketUrl = "wss://服务器域名/WebSocket/"

//OSS存储
// Config.imgUrl = "http://"

export { Config }

app.js代码

// app.js
import { Config } from 'utils/Config.js';
App({
  onLaunch() {
    // 小程序初始化装载的时候需要加载的东西
  },

// websocket
onShow:function(){
  // console.log("show")
  wx.onSocketOpen(function(){
    console.log("链接已经打开")
  })
  this.reconnect();
},
//建立websocket连接
linkSocket() {
  var that = this
  console.log("正在建立websocket连接")
  wx.connectSocket({
    url: that.globalData.ipw + "这里可以存放后端生成的每个用户的小程序秘钥",
    success() {
      that.initEventHandle()

    },
    fail() {
      // wx.hideLoading()
    }
  })
},

//绑定事件
initEventHandle() {
  var that = this
  wx.onSocketOpen(() => {
    //取消提示
    // wx.showToast({
    //   title: '连接成功!',
    //   icon: 'success',
    // })
    // wx.hideLoading()
    console.log('WebSocket连接打开')
    wx.setStorageSync('isWebsocket', 'true')
    that.sendSocketMessage({ // 发送的内容字段可以与后端人员协商
      "msg": "上线了",
      "role": "all",
      "hid": "7"
    })
  })

  wx.onSocketError((res) => { 
    // wx.hideLoading()
    wx.setStorageSync('isWebsocket', 'false')
    console.log("wx.onSocketError监听启动,并自动重连")
    // wx.showLoading({
    //   title: '网络错误',
    // })
    that.reconnect()
  })

  wx.onSocketClose((res) => {
    wx.setStorageSync('isWebsocket', 'false')
    // wx.hideLoading()
    //询问用户是否用户主动连接
    // console.log("wx.onSocketClose监听启动,并自动重连")
    // that.reconnect()
  })

  wx.onSocketMessage((result) => {
    console.log(JSON.parse(result.data))
  })
},
  //重新连接
  reconnect() {
    var that = this;
    // wx.showLoading({
    //   title: '重新连接中',
    //   duration:200,
    // })
    that.linkSocket();
  },
  sendSocketMessage(msg, callback) {
    msg = JSON.stringify(msg);
    wx.sendSocketMessage({
      data: msg,
      success: function (res) {
        console.log("app.js----wx.sendSocketMessage----->",res)
        var json = res.errMsg
        callback && callback(json)
      },
      fail: function () {

      }
    })
  },
  showReconnectModal() {
    var that = this
    wx.showModal({
      title: '提示',
      content: '网络断开,是否重连',
      success(res) {
        if (res.confirm) {
          that.reconnect()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  onHide(){
    console.log("onHide")
    wx.closeSocket()
    wx.onSocketOpen(function(e){
      console.log(e)
      wx.closeSocket()
    })    
    wx.onSocketClose(function(res){
      console.log("WebSocket 已关闭!")
    })
    
  },
//websocket



  globalData: {
    ipw: Config.webSocketUrl // 获取了配置文件config.js的websocket静态路径
  }
})

子页面案例代码(使用了自己封装的请求js文件直接复制会报错)

<view wx:if="{{rid==1002}}">
  <view class="top">
    <view class="float-r cu-bar search">
    <image class="cu-avatar add" src="/imgs/manage.png" bindtap="manage" ></image>
      <!-- <view class="cu-avatar round add" bindtap="manage" style="background-image:url('/imgs/manage.png');"></view> -->
    </view>
    <view class="float-r cu-bar search">
      <image class="cu-avatar add" src="/imgs/add.png" bindtap="add" ></image>
      <!-- <view class="cu-avatar round add" bindtap="add" style="background-image:url('/imgs/add.png');"></view> -->
    </view>
  </view>

  <view class='note' wx:for="{{details}}" data-id="{{index}}" bindtap="toDetail">
    <view class='note_time'>
      <text>{{item.ncreatedTime}}</text>
    </view>

    <view class='note bg-white'>
      <view class="note_img">
        <image src="{{item.nimg}}"></image>
      </view>

      <view>
        <text class='note_title'>{{item.ntitle}}</text>
      </view>

      <view>
        <text class='note_content'>{{item.ncontext}}</text>
      </view>
    </view>
  </view>
</view>

<view wx:if="{{rid==1001}}">
  <view class='note' wx:for="{{unreadlist}}" data-id="{{idx}}" bindtap="toDetail1" wx:for-index="idx">
    <view class='note_time'>
      <text>{{item.nCreatedTime}}</text>
    </view>

    <view class='note bg-white'>
      <view class="note_img">
        <image src="{{imglist[idx]}}"></image>
      </view>

      <view>
        <text class='note_title'>{{item.nTitle}}</text>
      </view>

      <view>
        <text class='note_content'>{{item.nContext}}</text>
      </view>
    </view>
  </view>
  <view style="text-align: center;margin-top: 50rpx;color: rgb(155,155,155);" wx:if="{{!readflag}}">暂无新消息</view>
  <view style="height: 40rpx;color: rgb(241,241,241);"></view>
</view>
.note {
  padding: 20rpx;
  margin-top: 20rpx;
}

.note_img {
  width: 100%;
}

.note_img image {
  width: 100%;
}

.note_title {
  font-size: 35rpx;
  font-weight: bold;
}

.note_time {
  margin: 0 auto;
  font-size: 25rpx;
  color: white;
  background-color: #dbdbdb;
  padding: 10rpx 20rpx;
  width: 270rpx;
  border-radius: 10rpx;
}

.note_content {
  margin-top: 5rpx;
  color: gray;
  font-size: 28rpx;
}

.top {
  background-color: #1296db;
  height: 100rpx;
}

.add {
  background-color: #1296db;
}

.float-r {
  float: right;
  margin-right: 10rpx;
}
var base = require('../../../utils/http');
import { Config } from '../../../utils/Config';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    details: [],
    unreadlist: [],
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    let pages = getCurrentPages();
    // 数组中索引最大的页面--当前页面
    let currentPage = pages[pages.length - 1];
    var rid = currentPage.options.rid
    var readflag=JSON.parse(currentPage.options.readflag)
    var uopenid = wx.getStorageSync('userinfo').uopenId
    var imglist = []
    for (var j = 0; j < wx.getStorageSync('websocket').unReadTotal; j++) {
      var nImg = Config.imgUrl + wx.getStorageSync('websocket').unReadMsg[j].nImg
      imglist = imglist.concat(nImg)
    }
    that.setData({
      rid: rid,
      unreadlist: wx.getStorageSync('websocket').unReadMsg,
      imglist: imglist,
      readflag:readflag
    })
    //   if(rid==1001){
    //     app.sendSocketMessage({
    //         "msg": "BuyCarPort",
    //         "UOpenId": wx.getStorageSync('userinfo').uopenId,
    //         "hid":"7",
    //         "role": 'all',
    //         "uid":wx.getStorageSync('userinfo').uid,
    //         "cid":that.data.cid
    //     })
    //   }
    base.http({
      method: 'post',
      url: 'Admin/getNoteListByAdmin',
      data: {
        token: wx.getStorageSync('token')
      },
      success(resa) {
        console.log('resa', resa)
        var array = resa.data
        var data = []
        var j = 0
        if(resa.code==20000){
        for (var i = 0; i < array.length; i++) {
          if (array[i].nstatus == 1) {
            data[j] = array[i]
            data[j].nimg = Config.imgUrl + data[j].nimg
            if(data[j].ncontext.length>15){
              data[j].ncontext = data[j].ncontext.substring(0,15) + '...'
            }
            j += 1
          }
        }
        that.setData({
          details: data
        })
      }
      }
    })
    // base.http({
    //   method:'post',
    //   url:Config.webSocketUrl+uopenid,
    //   data:{
    //     receiverOpenId:'host',
    //     msg:'sendToSA'
    //   },
    //   success(resw){
    //     console.log("resw",resw)
    //   }
    // })
  },

  toDetail: function (e) {
    var id = e.currentTarget.dataset.id
    var nid = this.data.details[id].nid
    wx.navigateTo({
      url: 'detail/detail?nid=' + nid,
    })
  },

  toDetail1: function (e) {
    console.log(e)
    var id = e.currentTarget.dataset.id
    var nid = this.data.unreadlist[id].nId
    var nTitle = this.data.unreadlist[id].nTitle
    var nCreatedTime = this.data.unreadlist[id].nCreatedTime
    var nContext = this.data.unreadlist[id].nContext
    wx.navigateTo({
      url: 'detail/detail?nid=' + nid + '&nTitle=' + nTitle + '&nCreatedTime=' + nCreatedTime + '&nContext=' + nContext+'&id='+id,
    })
  },

  add: function () {
    wx.navigateTo({
      url: 'add/add',
    })
  },

  manage: function () {
    wx.navigateTo({
      url: 'manage/manage',
    })
  },
})

效果图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oct1025

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值