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


Posted in Javascript onJuly 06, 2018

本文实例为大家分享了微信小程序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%
}

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

Javascript 相关文章推荐
发布BlueShow v1.0 图片浏览器(类似lightbox)blueshow.js 打包下载
Jul 21 Javascript
js 获取class的元素的方法 以及创建方法getElementsByClassName
Mar 11 Javascript
将文本输入框内容加入表中的js代码
Aug 18 Javascript
JS实现图片的不间断连续滚动的简单实例
Jun 03 Javascript
浅谈JS原生Ajax,GET和POST
Jun 08 Javascript
jQuery实现输入框邮箱内容自动补全与上下翻动显示效果【附demo源码下载】
Sep 20 Javascript
jquery实现瀑布流效果 jquery下拉加载新数据
Dec 12 Javascript
详解node-ccap模块生成captcha验证码
Jul 01 Javascript
Vue实现textarea固定输入行数与添加下划线样式的思路详解
Jun 28 Javascript
JS函数进阶之prototy用法实例分析
Jan 15 Javascript
vue中的过滤器及其时间格式化问题
Apr 09 Javascript
探究一道价值25k的蚂蚁金服异步串行面试题
Aug 21 Javascript
JavaScript实现的简单Tab点击切换功能示例
Jul 06 #Javascript
vue结合axios与后端进行ajax交互的方法
Jul 06 #Javascript
jQuery实现仿京东防抖动菜单效果示例
Jul 06 #jQuery
vue.js动画中的js钩子函数的实现
Jul 06 #Javascript
老生常谈JS中的继承及实现代码
Jul 06 #Javascript
vue.js使用v-if实现显示与隐藏功能示例
Jul 06 #Javascript
vue.js计算属性computed用法实例分析
Jul 06 #Javascript
You might like
Extended CHM PHP 语法手册之 DIY
2006/10/09 PHP
PHP生成便于打印的网页
2006/10/09 PHP
php 分页函数multi() discuz
2009/06/21 PHP
如何通过View::first使用Laravel Blade的动态模板详解
2017/09/21 PHP
tbody元素支持嵌套的注意方法
2007/03/24 Javascript
javascript 支持链式调用的异步调用框架Async.Operation
2009/08/04 Javascript
使用jQuery向asp.net Mvc传递复杂json数据-ModelBinder篇
2010/05/07 Javascript
转义字符(\)对JavaScript中JSON.parse的影响概述
2013/07/17 Javascript
javascript实现数字验证码的简单实例
2014/02/10 Javascript
JavaScript中用字面量创建对象介绍
2014/12/31 Javascript
jQuery实现字符串按指定长度加入特定内容的方法
2015/03/11 Javascript
javascript回到顶部特效
2016/07/30 Javascript
JavaScript中的this陷阱的最全收集并整理(没有之一)
2017/02/21 Javascript
用vue构建多页面应用的示例代码
2017/09/20 Javascript
AngularJS模糊查询功能实现代码(过滤内容下拉菜单排序过滤敏感字符验证判断后添加表格信息)
2017/10/24 Javascript
通过一个简单的例子学会vuex与模块化
2017/11/22 Javascript
javascript中的with语句学习笔记及用法
2020/02/17 Javascript
vue自定义指令限制输入框输入值的步骤与完整代码
2020/08/30 Javascript
vue radio单选框,获取当前项(每一项)的value值操作
2020/09/10 Javascript
pandas获取groupby分组里最大值所在的行方法
2018/04/20 Python
Python实现模拟登录网易邮箱的方法示例
2018/07/05 Python
python输出带颜色字体实例方法
2019/09/01 Python
Html5上传图片 移动端、PC端通用代码
2016/06/08 HTML / CSS
HTML5在a标签内放置块级元素示例代码
2013/08/23 HTML / CSS
大学生最新职业生涯规划书范文
2014/01/12 职场文书
生产部管理制度
2014/01/31 职场文书
研究生毕业自我鉴定范文
2014/03/27 职场文书
捐书活动总结
2014/05/04 职场文书
信用社竞聘演讲稿
2014/05/16 职场文书
借条如何写
2015/05/26 职场文书
幼儿体育课教学反思
2016/02/16 职场文书
最新的离婚协议书范本!
2019/07/02 职场文书
Nginx 过滤静态资源文件的访问日志的实现
2021/03/31 Servers
JS创建或填充任意长度数组的小技巧汇总
2021/10/24 Javascript
以下牛机,你有几个
2022/04/05 无线电
Python Numpy库的超详细教程
2022/04/06 Python