在微信小程序中利用WebSocket实现文字交流功能完整源码

该博客详细介绍了使用微信小程序(wxchat)实现一个基于WebSocket的实时聊天应用。包括UI部分的wxml结构,用于展示聊天记录和输入框,以及js部分的逻辑,如连接WebSocket、接收和发送消息。此外,还展示了wxss样式,定义了聊天界面的布局和元素样式。
摘要由CSDN通过智能技术生成

一、UI部分 wschat.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>

二、wschat.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)
  })
} 

三、wschat.wxss

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%
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为什么需要websocket? 传统的实时交互的游戏,或服务器主动发送消息的行为(如推送服务),如果想做在微信上,可能你会使用轮询的方式进行,不过这太消耗资源,大量的请求也加重了服务器的负担,而且延迟问题比较严重。如果是自己开发的app,为了解决这些问题,很多团队会自建socket,使用tcp长链接、自定协议的方式与服务器进行相对实时的数据交互。有能力的团队,采用这种方式自然没什么大问题。不过小团队可能就要花费很多时间去调试,要解决很多难题,这个在成本上就划不来。 H5引入了webSocket来解决网页端的长链接问题,而微信小程序也支持websocket。这是一个非常重要的特性,所以本系列的文章会专门拿出一篇来讨论websocketwebSocket本质上也是TCP连接,它提供全双工的数据传输。一方面可以避免轮询带来的连接频繁建立与断开的性能损耗,另一方面数据可以是比较实时的进行双向传输(因为是长链接),而且WebSocket允许跨域通信(这里有个潜在的跨域安全的问题,得靠服务端来解决)。目前除IE外的浏览器已经对webSocket支持得很好了,微信小程序再推一把之后,它会变得更加流行。 我们来设计一个新的demo,一个比较有趣的小游戏,多人版扫雷,准确地讲,多人版挖黄金。 游戏规则是这样的:把雷换成金子,挖到金子加一分,每人轮流一次(A挖完轮到B,B挖完A才能再点击),点金子就算你的,也不会炸,游戏继续,直到把场上所有的金子都挖完游戏才结束。跟扫雷一样,数字也是表示周边有几个金子,然后用户根据场上已经翻出来的数字来猜哪一格可能有金子。 这种交互的游戏难点在于,用户的点击操作都要传到服务器上,而且服务器要实时的推送到其它玩家的应用上。另外用户自己也要接收对方操作时实时传过来的数据,这样才不至于重复点同一个格子。简单讲,就是你要上报操作给服务器,而服务器也要实时给你推消息。为了简化整个模型,我们规定玩家必须轮流来点击,玩家A点完后,才能轮到玩家B,玩家B操作完,玩家A才能点。 我们分几步来实现这个功能。 一、实现思路 1、第一步,我们要先生成扫雷的地图场景 这个算法比较简单,简述一下。随机取某行某列就可以定位一个格子,标记成金子(-1表示金子)。mimeCnt表示要生成的金子的数量,用同样的方式循环标记mimeCnt个随机格子。生成完后,再用一个循环去扫描这些-1的格子,把它周边的格子都加1,当然必须是非金子的格子才加1。代码放在这里。 其increaseArround用来把这格金子周边的格子都加1,实现也比较简单: 执行genMimeArr(),随机生成结果如下: -1表示金子。看了下貌似没什么问题。接下去,我们就要接入webSocket了。 (这个是js版本的,其实生成地图场景的工作是在后台生成,这个js版本只是一个演示,不过算法是一样的。) 2、我们需要一个支持webSocket的服务端 本例子,我们使用python的tornado框架来实现(tornado提供了tornado.websocket模块)。当然读者也可以使用socket.io,专为webSocket设计的js语言的服务端,用起来非常简单,它也对不支持webSocket的浏览器提供了兼容(flash或comet实现)。 笔者本人比较喜欢使用tornado,做了几年后台开发,使用最多的框架之一的就是它,NIO模型,而且非常轻量级,同样的rps,java可能需要700-800M的内存,tornado只要30-40M,所以在一台4G内存的机子上可以跑上百个tornado服务,而java,对不起,只能跑3个虚拟机。微服务的时代,这一点对小公司很重要。当然如果读者本人对java比较熟悉的话,也可以选择netty框架尝试一下。 webSocket用tornado的另一个好处是,它可以在同一个服务(端口)上同时支持webSocket及http两种协议。tornado的官方demo代码展示了怎么实现同时使用两种协议。在本游戏,可以这么用:用户进入首页,用http协议去拉取当前的房间号及数据。因为首页是打开最多的,进了首页的用户不一定会玩游戏。所以首页还没必要建立webSocket链接,webSocket链接主要用来解决频繁请求及推送的操作。首页只有一个请求操作。选了房间号后,进去下一个游戏页面再开始建立webSocket链接。 3、客户端 使用微信小程序开发工具,直接连接是会报域名安全错误的,因为工具内部做了限制,对安全域名才会允许连接。所以同样的,这里我们也继续改下工具的源码,把相关的行改掉就行修改方式如下: 找到asdebug.js的这一行,把它改成: if(false)即可。
微信小程序Demo-学习用:修改长连接,练习用-附完整源代码.rar 资源介绍 本资源是一个微信小程序Demo,旨在帮助开发者学习和实践微信小程序的长连接(WebSocket)技术。通过修改和扩展这个示例,开发者可以更深入地理解WebSocket小程序的应用,为自己的项目添加实时通信功能。 该Demo包含了完整的源代码,基于微信小程序官方提供的开发框架搭建。主要特点如下: 1. 实现WebSocket客户端与服务器之间的长连接,支持发送和接收消息。 2. 提供了一个简单的用户界面,用于展示WebSocket连接的状态和接收到的消息。 3. 使用了微信小程序的WXS(微信脚本)来处理WebSocket相关的逻辑,以便更好地控制数据格式和传输效率。 4. 代码结构清晰,注释详细,方便初学者理解和学习。 开发者可以通过以下方式利用此资源进行学习和实践: 1. 下载并解压.rar文件,使用微信开发者工具打开项目。 2. 在开发过程,可以参考源代码的注释和文档,了解WebSocket的使用方法和注意事项。 3. 根据自己的需求,对源代码进行修改和扩展,实现更多功能。 4. 在实际项目应用所学知识,提高小程序的实时通信能力。 总之,本资源为开发者提供了一个很好的学习和实践平台,有助于掌握微信小程序WebSocket技术的应用。同时,它也是一个很好的起点,可以根据需要进行二次开发和定制,以满足不同项目的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值