欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

微信小程序WebSocket实现聊天对话功能

程序员文章站 2022-06-08 20:31:05
本文实例为大家分享了微信小程序websocket实现聊天对话功能的具体代码,供大家参考,具体内容如下 js var app = getapp(); var s...

本文实例为大家分享了微信小程序websocket实现聊天对话功能的具体代码,供大家参考,具体内容如下

js

var app = getapp();
var socketopen = false;
var framebuffer_data, session, sockettask;
var url = 'ws://请填写您的长链接接口地址';
var upload_url ='请填写您的图片上传接口地址'
page({
 data: {
  user_input_text: '',//用户输入文字
  inputvalue: '',
  returnvalue: '',
  addimg: false,
  //格式示例数据,可为空
  allcontentlist: [],
  num: 0
 },
 // 页面加载
 onload: function () {
  this.bottom();
 },
 onshow: function (e) {
  if (!socketopen) {
   this.websocket()
  }
 },
 // 页面加载完成
 onready: function () {
  var that = this;
  sockettask.onopen(res => {
   socketopen = true;
   console.log('监听 websocket 连接打开事件。', res)
  })
  sockettask.onclose(onclose => {
   console.log('监听 websocket 连接关闭事件。', onclose)
   socketopen = false;
   this.websocket()
  })
  sockettask.onerror(onerror => {
   console.log('监听 websocket 错误。错误信息', onerror)
   socketopen = false
  })
  sockettask.onmessage(onmessage => {
   console.log('监听websocket接受到服务器的消息事件。服务器返回的消息', 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)
    // 是否为数组
    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 () {
  // 创建socket
  sockettask = wx.connectsocket({
   url: url,
   data: 'data',
   header: {
    'content-type': 'application/json'
   },
   method: 'post',
   success: function (res) {
    console.log('websocket连接创建', res)
   },
   fail: function (err) {
    wx.showtoast({
     title: '网络异常!',
    })
    console.log(err)
   },
  })
 },
 
 // 提交文字
 submitto: function (e) {
  let that = this;
  var data = {
   body: that.data.inputvalue,
  }
 
  if (socketopen) {
   // 如果打开了socket就发送数据给服务器
   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('关闭 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: '图片发送成功!',
         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节点然后屏幕焦点调转到这个节点 
 bottom: function () {
  var that = this;
  this.setdata({
   scrolltop: 1000000
  })
 },
})
 
//通过 websocket 连接发送数据,需要先 wx.connectsocket,并在 wx.onsocketopen 回调之后才能发送。
function sendsocketmessage(msg) {
 var that = this;
 console.log('通过 websocket 连接发送数据', json.stringify(msg))
 sockettask.send({
  data: json.stringify(msg)
 }, function (res) {
  console.log('已发送', 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'>发送</button>
 </block>
 <block wx:if='{{addimg}}'>
  <view class='voice_ing' bindtap="upimg">发送图片</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%
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。