经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » 微信小程序 » 查看文章
详解微信小程序开发聊天室—实时聊天,支持图片预览
来源:jb51  时间:2019/5/20 10:50:02  对本文有异议

第一次写小程序,老板就让我用websoket写个聊天对话,群聊这种。第一次写聊天功能,第一次用websoket,第一次用小程序,这是在考验我吗?不过我还是研究了一下,终于实现了。

首先看一下界面,界面很简单,就是首页刚进来获取了用户信息头像,昵称等。点击进入聊天室就可以聊天了,下面我介绍的是前端代码实现,后台需要做的很简单,就是你给他发送什么数据,他就给你返回什么数据,就是在接收前台发送过来的图片的时候需要做个格式转换,因为有时候前端将接收到的json字符串转换json对象的时候,遇到有特殊的标点符号可能会报错,比如我就是‘\'报的错,找了半天。

因为有人咨询,所以附上所有小程序代码,地址:https://github.com/chongwenwen/weixin_chat/tree/master

有人说为什么没有utile.js的代码,这个功能只用到websoket.js跟utile.js没有关系哦!还有后台代码在页面最底下

         

        

文档目录结构如下:(聊天页面为chat)

  

chat.wxml页面

首先写好页面结构,既然是群聊功能,肯定有自己和别人,所以页面的view盒子应给有两部分,一个内容左侧显示,一个内容右侧显示,下面是代码,因为没有正式注册企业项目,我用的服务器都是本地的服务器,所以界面区分别人和我的聊天信息是用昵称区分的,如果正式项目应该是由一个用户标记去区分的

  1. <view class="news" bindtap='outbtn'>
  2. <view class="chat-notice" wx:if="{{userInfo}}">系统消息: 欢迎 {{ userInfo.nickName }} 加入群聊</view>
  3. <view class="historycon">
  4. <scroll-view scroll-y="true" class="history" scroll-top="{{scrollTop}}">
  5. <block wx:for="{{newslist}}" wx:key>
  6.     <!-- 历史消息 -->
  7. <!-- <view class="chat-news">
  8. <view style="text-align: left;padding-left: 20rpx;">
  9. <image class='new_img' src="{{item.avatarUrl? item.avatarUrl:'images/avator.png'}}"></image>
  10. <text class="name">{{ item.nickName }}{{item.date}}</text>
  11. </view>
  12. <view class='you_left'>
  13. <block wx:if="{{item.type=='text'}}">
  14. <view class='new_txt'>{{item.content}}</view>
  15. </block>
  16. <block wx:if="{{item.type=='image'}}">
  17. <image class="selectImg" src="{{item.images}}"></image>
  18. </block>
  19. </view>
  20. </view> -->
  21. <view>{{item.date}}</view>
  22. <!--自己的消息 -->
  23. <view class="chat-news" wx:if="{{item.nickName == userInfo.nickName}}">
  24. <view style="text-align: right;padding-right: 20rpx;">
  25. <text class="name">{{ item.nickName }}</text>
  26. <image class='new_img' src="{{userInfo.avatarUrl}}"></image>
  27. </view>
  28. <view class='my_right'>
  29. <block wx:if="{{item.type=='text'}}">
  30. <view class='new_txt'>{{item.content}}</view>
  31. </block>
  32. <block wx:if="{{item.type=='image'}}">
  33. <image class="selectImg" src="{{item.images}}" data-src="{{item.images}}" lazy-load="true" bindtap="previewImg"></image>
  34. </block>
  35. </view>
  36. </view>
  37. <!-- 别人的消息 -->
  38. <view class="chat-news" wx:else>
  39. <view style="text-align: left;padding-left: 20rpx;">
  40. <image class='new_img' src="{{item.avatarUrl? item.avatarUrl:'images/avator.png'}}"></image>
  41. <text class="name">{{ item.nickName }}</text>
  42. </view>
  43. <view class='you_left'>
  44. <block wx:if="{{item.type=='text'}}">
  45. <view class='new_txt'>{{item.content}}</view>
  46. </block>
  47. <block wx:if="{{item.type=='image'}}">
  48. <image class="selectImg" src="{{item.images}}" data-src="{{item.images}}" lazy-load="true" bindtap="previewImg"></image>
  49. </block>
  50. </view>
  51. </view>
  52. </block>
  53. </scroll-view>
  54. </view>
  55. </view>
  56. <view id="flag"></view>
  57. <!-- 聊天输入 -->
  58. <view class="message">
  59. <form bindreset="cleanInput" class="sendMessage">
  60. <input type="text" placeholder="请输入聊天内容.." value="{{massage}}" bindinput='bindChange'></input>
  61. <view class="add" bindtap='increase'>+</view>
  62. <button type="primary" bindtap='send' formType="reset" size="small" button-hover="blue">发送</button>
  63. </form>
  64. <view class='increased {{aniStyle?"slideup":"slidedown"}}' wx:if="{{increase}}">
  65. <view class="image" bindtap='chooseImage'>相册 </view>
  66. </view>
  67. </view>

websoket.js文件

在utils目录下,是封装了websoket的请求过程,以便在chat.js中调用。需要注意的是wx.connectSocket代表客户端首次和服务器建立联系,wx.onSocketOpen才是正式打开通道,wx.onSocketMessage必须在 wx.onSocketOpen 回调之后发送才生效。

wx.onSocketMessage里面带有参数是一个函数回调,这个回调就是后台服务器实时接收并返给前台的数据

  1. var url = 'ws://........';//服务器地址
  2. function connect(user,func) {
  3. wx.connectSocket({
  4. url: url,
  5. header:{'content-type': 'application/json'},
  6. success: function () {
  7. console.log('信道连接成功~')
  8. },
  9. fail: function () {
  10. console.log('信道连接失败~')
  11. }
  12. })
  13. wx.onSocketOpen(function (res) {
  14. wx.showToast({
  15. title: '信道已开通~',
  16. icon: "success",
  17. duration: 2000
  18. })
  19. //接受服务器消息
  20. wx.onSocketMessage(func);//func回调可以拿到服务器返回的数据
  21. });
  22. wx.onSocketError(function (res) {
  23. wx.showToast({
  24. title: '信道连接失败,请检查!',
  25. icon: "none",
  26. duration: 2000
  27. })
  28. })
  29. }
  30. //发送消息
  31. function send(msg) {
  32. wx.sendSocketMessage({
  33. data: msg
  34. });
  35. }
  36. module.exports = {
  37. connect: connect,
  38. send: send
  39. }

chat.js文件

聊天室的逻辑操作页面,websocket.connect(){}调用的是websocket.js封装好的websoket的逻辑函数,回调就是后台的数据,之所以在本页面调用就是方便接收以后的逻辑操作。我建立文件的时候用的就是微信官方的快速模板生成的,所以app.js里面没有变动,用户在chat.js获取userInfo的时候可以引用全局的app.globalData.userInfo

 还有要注意的一点就是在选择发送图片的时候,必须是先把本地的图片地址发送给后台,转换成服务器的图片地址再次通过wensoket.send发送给服务器,这个时候服务器推送给其他用户的才是正确的地址,否则你的本地地址其他用户是访问不到的。

  1. // pages/chat/chat.js
  2. const app = getApp()
  3. var websocket = require('../../utils/websocket.js');
  4. var utils = require('../../utils/util.js');
  5. Page({
  6. /**
  7. * 页面的初始数据
  8. */
  9. data: {
  10. newslist:[],
  11. userInfo: {},
  12. scrollTop: 0,
  13. increase:false,//图片添加区域隐藏
  14. aniStyle: true,//动画效果
  15. message:"",
  16. previewImgList:[]
  17. },
  18. /**
  19. * 生命周期函数--监听页面加载
  20. */
  21. onLoad: function () {
  22. var that = this
  23. if (app.globalData.userInfo) {
  24. this.setData({
  25. userInfo: app.globalData.userInfo
  26. })
  27. }
  28. //调通接口
  29. websocket.connect(this.data.userInfo, function (res) {
  30. // console.log(JSON.parse(res.data))
  31. var list = []
  32. list = that.data.newslist
  33. list.push(JSON.parse(res.data))
  34. that.setData({
  35. newslist: list
  36. })
  37. })
  38. },
  39. // 页面卸载
  40. onUnload(){
  41. wx.closeSocket();
  42. wx.showToast({
  43. title: '连接已断开~',
  44. icon: "none",
  45. duration: 2000
  46. })
  47. },
  48. //事件处理函数
  49. send: function () {
  50. var flag = this
  51. if (this.data.message.trim() == ""){
  52. wx.showToast({
  53. title: '消息不能为空哦~',
  54. icon: "none",
  55. duration: 2000
  56. })
  57. }else {
  58. setTimeout(function(){
  59. flag.setData({
  60. increase: false
  61. })
  62. },500)
  63. websocket.send('{ "content": "' + this.data.message + '", "date": "' + utils.formatTime(new Date()) + '","type":"text", "nickName": "' + this.data.userInfo.nickName + '", "avatarUrl": "' + this.data.userInfo.avatarUrl+'" }')
  64. this.bottom()
  65. }
  66. },
  67. //监听input值的改变
  68. bindChange(res) {
  69. this.setData({
  70. message : res.detail.value
  71. })
  72. },
  73. cleanInput(){
  74. //button会自动清空,所以不能再次清空而是应该给他设置目前的input值
  75. this.setData({
  76. message: this.data.message
  77. })
  78. },
  79. increase() {
  80. this.setData({
  81. increase: true,
  82. aniStyle: true
  83. })
  84. },
  85. //点击空白隐藏message下选框
  86. outbtn(){
  87. this.setData({
  88. increase: false,
  89. aniStyle: true
  90. })
  91. },
  92. //发送图片
  93. chooseImage() {
  94. var that = this
  95. wx.chooseImage({
  96. count: 1, // 默认9
  97. sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
  98. sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
  99. success: function (res) {
  100. // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
  101. var tempFilePaths = res.tempFilePaths
  102. // console.log(tempFilePaths)
  103. wx.uploadFile({
  104. url: 'http://.....', //服务器地址
  105. filePath: tempFilePaths[0],
  106. name: 'file',
  107. headers: {
  108. 'Content-Type': 'form-data'
  109. },
  110. success: function (res) {
  111. if (res.data){
  112. that.setData({
  113. increase: false
  114. })
  115. websocket.send('{"images":"'+ res.data +'","date":"'+utils.formatTime(new Date())+'","type":"image","nickName":"'+that.data.userInfo.nickName+'","avatarUrl":"'+that.data.userInfo.avatarUrl+'"}')
  116. that.bottom()
  117. }
  118. }
  119. })
  120. }
  121. })
  122. },
  123. //图片预览
  124. previewImg(e){
  125. var that = this
  126. //必须给对应的wxml的image标签设置data-set=“图片路径”,否则接收不到
  127. var res = e.target.dataset.src
  128. var list = this.data.previewImgList //页面的图片集合数组
  129. //判断res在数组中是否存在,不存在则push到数组中, -1表示res不存在
  130. if (list.indexOf(res) == -1 ) {
  131. this.data.previewImgList.push(res)
  132. }
  133. wx.previewImage({
  134. current: res, // 当前显示图片的http链接
  135. urls: that.data.previewImgList // 需要预览的图片http链接列表
  136. })
  137. },
  138. //聊天消息始终显示最底端
  139. bottom: function () {
  140. var query = wx.createSelectorQuery()
  141. query.select('#flag').boundingClientRect()
  142. query.selectViewport().scrollOffset()
  143. query.exec(function (res) {
  144. wx.pageScrollTo({
  145. scrollTop: res[0].bottom // #the-id节点的下边界坐标
  146. })
  147. res[1].scrollTop // 显示区域的竖直滚动位置
  148. })
  149. },
  150. })

最后是页面的样式文件chat.wxss

  1. /* pages/chat/chat.wxss */
  2. page {
  3. background-color: #f7f7f7;
  4. height: 100%;
  5. }
  6. /* 聊天内容 */
  7. .news {
  8. padding-top: 30rpx;
  9. text-align: center;
  10. /* height:100%; */
  11. box-sizing:border-box;
  12. }
  13. #flag{
  14. margin-bottom: 100rpx;
  15. height: 30rpx;
  16. }
  17. .chat-notice{
  18. text-align: center;
  19. font-size: 30rpx;
  20. padding: 10rpx 0;
  21. color: #666;
  22. }
  23. .historycon {
  24. height: 100%;
  25. width: 100%;
  26. /* flex-direction: column; */
  27. display: flex;
  28. border-top: 0px;
  29. }
  30. /* 聊天 */
  31. .chat-news{
  32. width: 100%;
  33. overflow: hidden;
  34. }
  35. .chat-news .my_right {
  36. float: right;
  37. /* right: 40rpx; */
  38. padding: 10rpx 10rpx;
  39. }
  40. .chat-news .name{
  41. margin-right: 10rpx;
  42. }
  43. .chat-news .you_left {
  44. float: left;
  45. /* left: 5rpx; */
  46. padding: 10rpx 10rpx;
  47. }
  48. .selectImg{
  49. display: inline-block;
  50. width: 150rpx;
  51. height: 150rpx;
  52. margin-left: 50rpx;
  53. }
  54. .my_right .selectImg{
  55. margin-right: 80rpx;
  56. }
  57. .new_img {
  58. width: 60rpx;
  59. height: 60rpx;
  60. border-radius: 50%;
  61. vertical-align: middle;
  62. margin-right: 10rpx;
  63. }
  64. .new_txt {
  65. max-width: 300rpx;
  66. display: inline-block;
  67. border-radius: 6rpx;
  68. line-height: 60rpx;
  69. background-color: #95d4ff;
  70. padding: 5rpx 20rpx;
  71. margin: 0 10rpx;
  72. margin-left: 50rpx;
  73. }
  74. .my_right .new_txt{
  75. margin-right:60rpx;
  76. }
  77. .you{
  78. background-color: lightgreen;
  79. }
  80. .my {
  81. border-color: transparent transparent transparent #95d4ff;
  82. }
  83. .you {
  84. border-color: transparent #95d4ff transparent transparent;
  85. }
  86. .hei{
  87. margin-top: 50px;
  88. height: 20rpx;
  89. }
  90. .history {
  91. height: 100%;
  92. margin-top: 15px;
  93. padding: 10rpx;
  94. font-size: 14px;
  95. line-height: 40px;
  96. word-break: break-all;
  97. }
  98. ::-webkit-scrollbar {
  99. width: 0;
  100. height: 0;
  101. color: transparent;
  102. z-index: -1;
  103. }
  104. /* 信息输入区域 */
  105. .message{
  106. position: fixed;
  107. bottom:0;
  108. width: 100%;
  109. }
  110. .sendMessage{
  111. display: block;
  112. height: 80rpx;
  113. padding: 10rpx 10rpx;
  114. background-color: #fff;
  115. border-top: 2rpx solid #eee;
  116. border-bottom: 2rpx solid #eee;
  117. z-index:3;
  118. }
  119. .sendMessage input{
  120. float:left;
  121. width: 66%;
  122. height: 100%;
  123. line-height: 80rpx;
  124. border-bottom: 1rpx solid #ccc;
  125. padding:0 10rpx;
  126. font-size: 35rpx;
  127. color: #666;
  128. }
  129. .sendMessage view{
  130. display: inline-block;
  131. width: 80rpx;
  132. height: 80rpx;
  133. line-height: 80rpx;
  134. font-size: 60rpx;
  135. text-align: center;
  136. color: #999;
  137. border: 1rpx solid #ccc;
  138. border-radius: 50%;
  139. margin-left: 10rpx;
  140. }
  141. .sendMessage button {
  142. float: right;
  143. font-size: 35rpx;
  144. }
  145. .increased{
  146. width:100%;
  147. /* height: 150rpx; */
  148. padding: 40rpx 30rpx;
  149. background-color: #fff;
  150. }
  151. .increased .image{
  152. width: 100rpx;
  153. height: 100rpx;
  154. border: 3rpx solid #ccc;
  155. line-height: 100rpx;
  156. text-align: center;
  157. border-radius: 8rpx;
  158. font-size:35rpx;
  159. }
  160. @keyframes slidedown {
  161. from {
  162. transform: translateY(0);
  163. }
  164. to {
  165. transform: translateY(100%);
  166. }
  167. }
  168. .slidedown {
  169. animation: slidedown 0.5s linear ;
  170. }
  171. .slideup {
  172. animation: slideup 0.5s linear ;
  173. }
  174. @keyframes slideup {
  175. from {
  176. transform: translateY(100%);
  177. }
  178. to {
  179. transform: translateY(0);
  180. }
  181. }

后台代码(图片):

以上所述是小编给大家介绍的微信小程序实时聊天支持图片预览详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对w3xue网站的支持!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号