使用node.js实现微信小程序实时聊天功能

2020-06-17 06:53:40易采站长站整理

<!-- 我这用的是自己另一个服务的图片 -->
<image class='touimg' src='https://www.tjjxsoft.cn/static/images/img005.png'></image>
</view>
<view>{{item.msg}}</view>
</view>
</view>
<view wx:else class='rightView'>
<view class='name'>{{item.user.name}}</view>
<view class='imgmsg'>
<view>{{item.msg}}</view>
<view>
<!-- 我这用的是自己另一个服务的图片 -->
<image class='touimg' src='https://www.tjjxsoft.cn/static/images/img005.png'></image>
</view>
</view>
</view>
</block>
</view>
</scroll-view>
<view class='sendView'>
<input bindinput='sendTextBind' placeholder="输入聊天内容" value='{{sendText}}' />
<button bindtap='sendBtn' type="primary">发送</button>
</view>
</view>

js:


var app = getApp();
Page({
data: {
socket_open: false,//判断连接是否打开
sendText: "",//发送的消息
serverMsg: [],//接受的服务端的消息
userInfo: { userId: 1, name: "呵呵",img:'头像'},//app.appData.userInfo,
scrolltop: 999
},
/**输入内容 */
sendTextBind: function(e) {
this.setData({
sendText: e.detail.value
});
console.log(this.data.sendText);
},
/**发送消息 */
sendBtn: function(e) {
console.log('发送消息事件!');
var msgJson = {
user: {
id: this.data.userInfo.userId,//app.appData.userInfo.userId, //唯一ID区分身份
name: this.data.userInfo.name, //显示用姓名
img: this.data.userInfo.img, //显示用头像
},
msg: this.data.sendText,//发送的消息
groupid:1
}
//发送消息
this.send_socket_message(JSON.stringify(msgJson));
this.setData({
sendText: ""//发送消息后,清空文本框
});
},
onLoad: function(options) {
// app.login();
// this.setData({
// userInfo: app.appData.userInfo
// });
//初始化
this.wssInit();
},
wssInit() {
var that = this;
//建立连接
wx.connectSocket({
url: 'ws://localhost'//app.appData.socket
})
//监听WebSocket连接打开事件。
wx.onSocketOpen(function(res) {
console.log('WebSocket连接已打开!');
that.setData({
socket_open: true
});
});
//监听WebSocket接受到服务器的消息事件。