微信小程序WebSocket實(shí)現(xiàn)聊天對(duì)話功能
本文實(shí)例為大家分享了微信小程序WebSocket實(shí)現(xiàn)聊天對(duì)話功能的具體代碼,供大家參考,具體內(nèi)容如下
js
var app = getApp();
var socketOpen = false;
var frameBuffer_Data, session, SocketTask;
var url = 'ws://請(qǐng)?zhí)顚?xiě)您的長(zhǎng)鏈接接口地址';
var upload_url ='請(qǐng)?zhí)顚?xiě)您的圖片上傳接口地址'
Page({
data: {
user_input_text: '',//用戶輸入文字
inputValue: '',
returnValue: '',
addImg: false,
//格式示例數(shù)據(jù),可為空
allContentList: [],
num: 0
},
// 頁(yè)面加載
onLoad: function () {
this.bottom();
},
onShow: function (e) {
if (!socketOpen) {
this.webSocket()
}
},
// 頁(yè)面加載完成
onReady: function () {
var that = this;
SocketTask.onOpen(res => {
socketOpen = true;
console.log('監(jiān)聽(tīng) WebSocket 連接打開(kāi)事件。', res)
})
SocketTask.onClose(onClose => {
console.log('監(jiān)聽(tīng) WebSocket 連接關(guān)閉事件。', onClose)
socketOpen = false;
this.webSocket()
})
SocketTask.onError(onError => {
console.log('監(jiān)聽(tīng) WebSocket 錯(cuò)誤。錯(cuò)誤信息', onError)
socketOpen = false
})
SocketTask.onMessage(onMessage => {
console.log('監(jiān)聽(tīng)WebSocket接受到服務(wù)器的消息事件。服務(wù)器返回的消息', JSON.parse(onMessage.data))
var onMessage_data = JSON.parse(onMessage.data)
if (onMessage_data.cmd == 1) {
that.setData({
link_list: text
})
console.log(text, text instanceof Array)
// 是否為數(shù)組
if (text instanceof Array) {
for (var i = 0; i < text.length; i++) {
text[i]
}
} else {
}
that.data.allContentList.push({ is_ai: true, text: onMessage_data.body });
that.setData({
allContentList: that.data.allContentList
})
that.bottom()
}
})
},
webSocket: function () {
// 創(chuàng)建Socket
SocketTask = wx.connectSocket({
url: url,
data: 'data',
header: {
'content-type': 'application/json'
},
method: 'post',
success: function (res) {
console.log('WebSocket連接創(chuàng)建', res)
},
fail: function (err) {
wx.showToast({
title: '網(wǎng)絡(luò)異常!',
})
console.log(err)
},
})
},
// 提交文字
submitTo: function (e) {
let that = this;
var data = {
body: that.data.inputValue,
}
if (socketOpen) {
// 如果打開(kāi)了socket就發(fā)送數(shù)據(jù)給服務(wù)器
sendSocketMessage(data)
this.data.allContentList.push({ is_my: { text: this.data.inputValue }});
this.setData({
allContentList: this.data.allContentList,
inputValue: ''
})
that.bottom()
}
},
bindKeyInput: function (e) {
this.setData({
inputValue: e.detail.value
})
},
onHide: function () {
SocketTask.close(function (close) {
console.log('關(guān)閉 WebSocket 連接。', close)
})
},
upimg: function () {
var that = this;
wx.chooseImage({
sizeType: ['original', 'compressed'],
success: function (res) {
that.setData({
img: res.tempFilePaths
})
wx.uploadFile({
url: upload_url,
filePath: res.tempFilePaths,
name: 'img',
success: function (res) {
console.log(res)
wx.showToast({
title: '圖片發(fā)送成功!',
duration: 3000
});
}
})
that.data.allContentList.push({ is_my: { img: res.tempFilePaths } });
that.setData({
allContentList: that.data.allContentList,
})
that.bottom();
}
})
},
addImg: function () {
this.setData({
addImg: !this.data.addImg
})
},
// 獲取hei的id節(jié)點(diǎn)然后屏幕焦點(diǎn)調(diào)轉(zhuǎn)到這個(gè)節(jié)點(diǎn)
bottom: function () {
var that = this;
this.setData({
scrollTop: 1000000
})
},
})
//通過(guò) WebSocket 連接發(fā)送數(shù)據(jù),需要先 wx.connectSocket,并在 wx.onSocketOpen 回調(diào)之后才能發(fā)送。
function sendSocketMessage(msg) {
var that = this;
console.log('通過(guò) WebSocket 連接發(fā)送數(shù)據(jù)', JSON.stringify(msg))
SocketTask.send({
data: JSON.stringify(msg)
}, function (res) {
console.log('已發(fā)送', res)
})
}
wxml
<view class='page_bg' wx:if='{{block}}' bindtap='hide_bg' />
<view class='btn_bg' wx:if='{{block}}'>
<view wx:for="{{link_list}}" wx:key='index'>
<button class="sp_tit" id='{{index}}' bindtap='list_item'>查看詳情 {{item}} </button>
</view>
</view>
<scroll-view class="history" scroll-y="true" scroll-with-animation scroll-top="{{scrollTop}}">
<block wx:key="{{index}}" wx:for="{{allContentList}}">
<!-- <view>
<text class='time'>{{time}}</text>
</view> -->
<view class='my_right' wx:if="{{item.is_my}}">
<view class='p_r' wx:if='{{item.is_my.text}}'>
<text class='new_txt'><text class='new_txt_my'>{{item.is_my.text}}</text></text>
<view class='sanjiao my'></view>
<image class='new_img' src='/images/test.jpg'></image>
</view>
<view class='p_r' wx:if='{{item.is_my.img}}' bindtap='my_audio_click' data-id='{{index}}'>
<text class='new_txt'> </text>
<view class='my_img_bg'>
<image class='my_audio' src='{{img}}'></image></view>
<view class='sanjiao my'></view>
<image class='new_img' src='/images/test.jpg'></image>
</view>
</view>
<!-- <view class='you_left' id='id_{{allContentList.length}}'> -->
<view class='you_left' id='id_{{allContentList.length}}' wx:key="{{index}}" wx:if="{{item.is_ai}}">
<view class='p_r'>
<image class='new_img' src='/images/chac.jpg'></image>
<view class='sanjiao you'></view>
<view class='new_txt'>
<view class='new_txt_ai'>
<!-- {{item.text}} -->
<block wx:for='{{item.is_two}}' wx:key='index'>
<text wx:if='{{item.text}}'>{{item.text}}</text>
<text wx:if='{{item.a.title}}' style='color:#0000EE' bindtap='link' id='{{item.a.link}}'>{{item.a.title}}</text>
</block>
</view>
</view>
</view>
</view>
</block>
</scroll-view>
<view class="sendmessage">
<image class='voice_icon' bindtap='addImg' src='/images/jia_img.png'></image>
<block wx:if='{{!addImg}}'>
<input type="text" bindinput="bindKeyInput" value='{{inputValue}}' focus='{{focus}}' bindfocus="focus" confirm-type="done" placeholder="" />
<button bindtap="submitTo" class='user_input_text'>發(fā)送</button>
</block>
<block wx:if='{{addImg}}'>
<view class='voice_ing' bindtap="upimg">發(fā)送圖片</view>
</block>
</view>
css
page {
background-color: #f2f2f2;
height: 100%;
}
.jia_img{
height: 80rpx;
width: 90rpx;
}
.time {
text-align: center;
padding: 5rpx 20rpx 5rpx 20rpx;
width: 200rpx;
font-size: 26rpx;
background-color: #E8E8E8;
}
.tab{
bottom: 120rpx;
}
.tab_1{
position: fixed;
bottom: 50rpx;
width: 200rpx;
font-size: 26rpx;
left: 50%;
margin-left: -45rpx;
height: 100rpx;
}
.tab_2{
right: 30rpx;
position: fixed;
}
/* 聊天 */
.my_right {
float: right;
margin-top: 30rpx;
position: relative;
right: 40rpx;
}
.my_audio{
height: 120rpx;
width: 150rpx;
position: absolute;
right: 150rpx;
background: white;
top: 20rpx;
}
.my_img_bg{
height: 150rpx;
width: 400rpx;
position: relative;
right: 0;
background: white;
top: 20rpx;
}
.you_left {
margin-top: 30rpx;
float: left;
position: relative;
left: 5rpx;
}
.new_img {
width: 100rpx;
height: 100rpx;
border-radius: 50%;
}
.new_txt {
width: 420rpx;
}
.new_txt_my{
border-radius: 7px;
background-color: #fff;
margin-top: 10rpx;
padding: 0rpx 30rpx 0rpx 30rpx;
float: right;
}
.new_txt_ai{
border-radius: 7px;
background-color: #fff;
margin-top: 10rpx;
padding: 0rpx 30rpx 0rpx 30rpx;
float: left;
}
.sanjiao {
top: 25rpx;
position: relative;
width: 0px;
height: 0px;
border-width: 15rpx;
border-style: solid;
}
.my {
border-color: transparent transparent transparent #fff;
}
.you {
border-color: transparent #fff transparent transparent;
}
.sendmessage {
width: 100%;
z-index: 2;
display: flex;
position: fixed;
bottom: 0px;
background-color: #F4F4F6;
flex-direction: row;
height: 85rpx;
}
.voice_icon{
width: 60rpx;
height: 60rpx;
margin: 0 auto;
padding: 10rpx 10rpx 10rpx 10rpx;
}
.voice_ing{
width: 90%;
height: 75rpx;
line-height: 85rpx;
text-align: center;
border-radius: 15rpx;
border: 1px solid #d0d0d0;
}
.sendmessage_2 {
z-index: 1;
position: relative;
width: 100%;
display: flex;
background-color: #F4F4F6;
flex-direction: row;
height: 85rpx;
}
.sendmessage input {
width: 75%;
height: 60rpx;
background-color: white;
line-height: 60rpx;
font-size: 28rpx;
border-radius: 10rpx;
margin-top: 10rpx;
margin-left: 20rpx;
border: 1px solid #d0d0d0;
padding-left: 20rpx;
}
.sendmessage button {
border: 1px solid white;
width: 18%;
height: 65rpx;
background: #00CC00;
color: white;
line-height: 65rpx;
margin-top: 10rpx;
font-size: 28rpx;
}
.hei{
height: 20rpx;
}
.history {
height: 80%;
padding: 20rpx 20rpx 20rpx 20rpx;
font-size: 14px;
line-height: 50rpx;
word-break: break-all;
}
.icno_kf{
position: fixed;
bottom: 160rpx;
margin: 0 auto;
text-align: center;
left: 50%;
margin-left: -40rpx;
width: 100rpx;
height: 100rpx;
border-radius: 50%
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript實(shí)現(xiàn)網(wǎng)頁(yè)跨年倒計(jì)時(shí)
這篇文章主要為大家詳細(xì)介紹了JavaScript實(shí)現(xiàn)網(wǎng)頁(yè)跨年倒計(jì)時(shí),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12
游覽器中javascript的執(zhí)行過(guò)程(圖文)
在講這個(gè)問(wèn)題之前,先來(lái)補(bǔ)充幾個(gè)知識(shí)點(diǎn),如果對(duì)此已經(jīng)比較了解可以直接跳過(guò)2012-05-05
詳解bootstrap-fileinput文件上傳控件的親身實(shí)踐
這篇文章主要介紹了詳解bootstrap-fileinput文件上傳控件的親身實(shí)踐,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-03-03
全面接觸神奇的Bootstrap導(dǎo)航條實(shí)戰(zhàn)篇
導(dǎo)航條(navbar)在Bootstrap中是一個(gè)獨(dú)立組件,導(dǎo)航條(navbar)和導(dǎo)航(nav)在Bootstrap中是有明顯區(qū)別的,本文全面接觸神奇的Bootstrap導(dǎo)航條,感興趣的小伙伴們可以參考一下2016-08-08
使用JavaScript刪除HTML元素的2種方法及3種情況
給定一個(gè)HTML元素,如何使用JavaScript從文檔中刪除該HTML元素,這篇文章主要給大家介紹了關(guān)于使用JavaScript刪除HTML元素的2種方法及3種情況,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01
JavaScript String(字符串)對(duì)象的簡(jiǎn)單實(shí)例(推薦)
下面小編就為大家?guī)?lái)一篇JavaScript String(字符串)對(duì)象的簡(jiǎn)單實(shí)例(推薦)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-08-08

