微信小程序WebSocket实现聊天对话功能完整源码

微信小程序WebSocket实现聊天对话功能完整源码微信小程序开发交流qq群173683895承接微信小程序开发。扫码加微信。正文:jsvarapp=getApp();varsocketOpen=false;varframeBuffer_Data,session,SocketTask;varurl=’ws://请填写您的长链接接口地址’;varupload_url=’请填写您的图片上…

大家好,又见面了,我是你们的朋友全栈君。

相关文章:

1.小程序聊天群,发送语音,文字,图片。

2.微信小程序集成腾讯IM,实现实时音视频通话,1V1聊天

3.云开发微信小程序聊天群

4.接入网易云信IM即时通讯的微信小程序聊天室

5.微信小程序聊天功能 WebSocket 实现发送文字,图片,语音以及WebSocket 常见问题解决方案

6.[微信小程序]聊天对话(文本,图片)的功能(完整代码附效果图)

如果有个性化的需要修改,可以联系我的微信

微信小程序开发交流qq群   173683895

微信小程序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%
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/150341.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • go语言环境安装教程_go语言菜鸟教程

    go语言环境安装教程_go语言菜鸟教程windows下go语言环境搭建安装1、go安装包下载:https://studygolang.com/dl选择自己要下载的版本进行下载。下载好了之后安装一直next就行了(安装路径尽量不要出现中文。)2、安装好了之后打开cmd,输入goversion查一下是否安装成功。出现go版本号,说明安装成功。3、下载liteidehttps://sourceforge.net/pro…

    2022年10月12日
    3
  • 网站渗透测试

    网站渗透测试目录[TOC]公司的网站需要渗透测试,学习了一下渗透测试的方法,记录下,方便后期查阅。(1)暴力激活成功教程1.1风险分析:数据传输过程使用非加密的http协议,因此可对数据传输过程进行抓包分析;用户名、密码明文,且未设置验证码,导致可进行暴力激活成功教程,以获取身份凭证信息1.2加固建议1:使用https加密传输可以在apache或者tomcat下配置好证书,启用https就ok,网上很多

    2022年6月16日
    27
  • 基于Ubuntu 的 Parrot ARDrone 2.0的SDK安装以及ardrone_autonomy和tum_ardrone的安装和使用

    基于Ubuntu 的 Parrot ARDrone 2.0的SDK安装以及ardrone_autonomy和tum_ardrone的安装和使用经过了一个多星期的摸索,现在开始慢慢理解ParrotARDrone2.0的使用。现在总结一下遇到的问题,希望用这款无人机的人能够得到一些帮助,毕竟不能总是做一个伸手党。ParrotARDrone2.0是法国的一家无人机的厂商生产的无人机的产品,是parrotardrone1.0的进阶版,摸索的这一个星期我感受到现在对ardrone2.0的支持还是挺棒的。有很多资料,遇到问题

    2022年8月15日
    8
  • pycharm如何调试代码_pycharm怎么分段运行代码

    pycharm如何调试代码_pycharm怎么分段运行代码最全Pycharm教程(1)——定制外观  最全Pycharm教程(2)——代码风格  1、准备工作  (1)Python版本为2.7或者更高版本  (2)已经创建了一个python工程并且添加了内容,具体参考: GettingStartedtutorial  2、第一步——运行代码  打开之前编写的Solver.py文件,在编辑框中右键,选

    2022年8月27日
    6
  • c#窗体添加背景音乐_eclipse怎么添加背景音乐

    c#窗体添加背景音乐_eclipse怎么添加背景音乐一.在项目中新建一个文件夹,然后将音乐文件导入:二.添加音乐代码如下:usingSystem.Media;//在命名空间中添加stringegm=”../../music/3.wav”;//定义变量来存储音频路径SoundPlayerbgm=newSoundPlayer(egm);//控制声音播放bgm.Play();//开始播放音乐bgm.Stop();//停……

    2025年10月13日
    4
  • TOF相机基本知识

    TOF相机基本知识TOF是Timeofflight的简写,直译为飞行时间的意思。所谓飞行时间法3D成像,是通过给目标连续发送光脉冲,然后利用传感器接收从物体返回的光,通过探测光脉冲的飞行时间来得到目标物的距离。TOF的深度精度不随距离改变而变化,基本能稳定在cm级。1TOF相机的特点:相对二维图像,可通过距离信息获取物体之间更加丰富的位置关系,即区分前景与后景深度信息依旧可以完成对目标图像

    2022年5月9日
    97

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号