功能架构图
![](https://img-blog.csdnimg.cn/e6795bed779e494ba2d7450627110848.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAb2N0MTAyNQ==,size_10,color_FFFFFF,t_70,g_se,x_16)
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',
})
},
})
效果图
![](https://img-blog.csdnimg.cn/90413c5d99d14332b8be6f3028812590.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAb2N0MTAyNQ==,size_12,color_FFFFFF,t_70,g_se,x_16)
![](https://img-blog.csdnimg.cn/a48e6dd5a1884fc69251bdfb699732d8.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAb2N0MTAyNQ==,size_12,color_FFFFFF,t_70,g_se,x_16)
![](https://img-blog.csdnimg.cn/4e6c5cfe31b64642b1fe6c0e8297c5d7.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAb2N0MTAyNQ==,size_12,color_FFFFFF,t_70,g_se,x_16)