经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » 微信小程序 » 查看文章
如何利用微信小程序和php实现即时通讯聊天功能
来源:jb51  时间:2022/4/11 10:25:52  对本文有异议

一、PHP7安装Swoole扩展

PHP swoole 扩展下载地址

Github:https://github.com/swoole/swoole-src/tags

php官方扩展库:http://pecl.php.net/package/swoole

开源中国:http://git.oschina.net/swoole/swoole/tags

1、自定义安装

  1. # 下载
  2. wget https://pecl.php.net/get/swoole-4.3.3.tgz
  3. # 解压
  4. tar zxf swoole-4.3.3.tgz
  5. # 编译安装扩展
  6. # 进入目录
  7. cd swoole-4.3.3
  8. # 执行phpize命令,产生出configure可执行文件
  9. # 如果不知道phpize路径在哪里 可以使用which phpize查看相应路径
  10. /usr/bin/phpize
  11. # 进行配置 如果不知道php-config路径在哪里 可以使用which php-config 查看相应路径
  12. ./configure --with-php-config=/usr/bin/php-config
  13. # 编译和安装
  14. make && make install
  15. vi /etc/php.ini
  16. 复制如下代码
  17. extension=swoole.so
  18. 放到你所打开或新建的文件中即可,无需重启任何服务
  19. # 查看扩展是否安装成功
  20. php -m|grep swoole

2、宝塔面板安装PHP swoole扩展

如果感觉上述安装较为复杂,可以使用宝塔面板实现一键安装

二、配置nginx反向代理

1、使用xshell连接远程阿里云服务器

2、使用命令(find / -name nginx.conf)查找nginx.conf所在的配置文件

3、使用命令(vim /etc/nginx/nginx.conf)查找进入到vim编辑器

查看到可以引入/etc/nginx/conf.d/下的配置文件信息

4、使用命令(cd /etc/nginx/conf.d/)进入到该路径下,并新建配置文件:study.lishuo.net.conf

5、配置nginx反向代理,实现访问study.lishuo.net域名转发端口号到127.0.0.1:9511也就是转发到webscoket运行的端口号        

  1. # 反向代理的规则 study 这个名字自己随便起
  2. upstream study{
  3. server 127.0.0.1:9511;
  4. }
  5. server {
  6. listen 80;
  7. server_name study.lishuo.net;
  8. error_page 404 /404.html;
  9. location = /404.html {
  10. }
  11. location / {
  12. index index.php index.html index.htm;
  13. if (!-e $request_filename) {
  14. rewrite ^(.*)$ /index.php?s=/$1 last;
  15. }
  16. #wss配置
  17. client_max_body_size 100m;
  18. proxy_redirect off;
  19. proxy_set_header Host $host;# http请求的主机域名
  20. proxy_set_header X-Real-IP $remote_addr;# 远程真实IP地址
  21. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;#反向代理之后转发之前的IP地址
  22. proxy_read_timeout 604800s;#websocket心跳时间,默认是60s
  23. proxy_http_version 1.1;
  24. proxy_set_header Upgrade $http_upgrade;
  25. proxy_set_header Connection "Upgrade";
  26. proxy_pass http://study;
  27. }
  28. error_page 500 502 503 504 /50x.html;
  29. location = /50x.html {
  30. }
  31. #添加下列信息,配置Nginx通过fastcgi方式处理您的PHP请求。
  32. location ~ .php$ {
  33. fastcgi_pass 127.0.0.1:9001; #Nginx通过本机的9000端口将PHP请求转发给PHP-FPM进行处理。
  34. fastcgi_index index.php;
  35. fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  36. include fastcgi_params; #Nginx调用fastcgi接口处理PHP请求。
  37. }
  38. }

三、微信小程序socket合法域名配置

1、登录到微信开放平台https://mp.weixin.qq.com/

2、开发=>开发管理=>开发设置,完成合法域名设置

3、到此配置已经完成了,接下来就是功能实现了,微信小程序+PHP代码

四、效果演示和代码

1、小程序端代码

小程序页面代码所在路径 /pages/contact/contact.wxml

  1. <!--pages/contact/contact.wxml-->
  2. <view>
  3. <scroll-view scroll-y scroll-into-view='{{toView}}' style='height: {{scrollHeight}};'>
  4. <!-- <view class='scrollMsg'> -->
  5. <block wx:key wx:for='{{msgList}}' wx:for-index="index">
  6. <!-- 单个消息1 客服发出(左) -->
  7. <view wx:if='{{item.speaker=="server"}}' id='msg-{{index}}' style='display: flex; padding: 2vw 11vw 2vw 2vw;'>
  8. <view style='width: 11vw; height: 11vw;'>
  9. <image style='width: 11vw; height: 11vw; border-radius: 10rpx;' src='https://cdn.pixabay.com/photo/2020/02/10/12/47/girl-4836394__340.jpg'></image>
  10. </view>
  11. <view style='width: 4vw; height: 11vw; margin-left: 0.5vw; display: flex; align-items: center; z-index: 9;'>
  12. <view class="triangle_border_left"></view>
  13. </view>
  14. <view class='leftMsg'>{{item.content}}</view>
  15. </view>
  16. <!-- 单个消息2 用户发出(右) -->
  17. <view wx:else id='msg-{{index}}' style='display: flex; justify-content: flex-end; padding: 2vw 2vw 2vw 11vw;'>
  18. <view class='rightMsg'>{{item.content}}</view>
  19. <view style='width: 4vw; height: 11vw; margin-right: 0.5vw; display: flex; align-items: center; z-index: 9;'>
  20. <view class="triangle_border_right"></view>
  21. </view>
  22. <view style='width: 11vw; height: 11vw;'>
  23. <image style='width: 11vw; height: 11vw; border-radius: 10rpx;' src='https://cdn.pixabay.com/photo/2021/09/24/10/00/chick-6652163__340.jpg'></image>
  24. </view>
  25. </view>
  26. </block>
  27. <!-- </view> -->
  28. <!-- 占位 -->
  29. <view style='width: 100%; height: 18vw;'></view>
  30. </scroll-view>
  31. <view class='inputRoom' style='bottom: {{inputBottom}}'>
  32. <image style='width: 7vw; margin-left: 3.2vw;' src='https://img95.699pic.com/element/40030/6429.png_300.png' mode='widthFix'></image>
  33. <input bindconfirm='sendClick' adjust-position='{{false}}' value='{{inputVal}}' confirm-type='send' bindfocus='focus' bindblur='blur'></input>
  34. </view>
  35. </view>

2、小程序页面样式代码所在路径 /pages/contact/contact.wxss

  1. /* pages/contact/contact.wxss */
  2. page {
  3. background-color: #f1f1f1;
  4. }
  5. .inputRoom {
  6. width: 100vw;
  7. height: 16vw;
  8. border-top: 1px solid #cdcdcd;
  9. background-color: #f1f1f1;
  10. position: fixed;
  11. bottom: 0;
  12. display: flex;
  13. align-items: center;
  14. z-index: 20;
  15. }
  16. input {
  17. width: 76vw;
  18. height: 9.33vw;
  19. background-color: #fff;
  20. border-radius: 40rpx;
  21. margin-left: 2vw;
  22. padding: 0 3vw;
  23. font-size: 28rpx;
  24. color: #444;
  25. }
  26. .leftMsg {
  27. font-size: 35rpx;
  28. color: #444;
  29. line-height: 7vw;
  30. padding: 2vw 2.5vw;
  31. background-color: #fff;
  32. margin-left: -1.6vw;
  33. border-radius: 10rpx;
  34. z-index: 10;
  35. }
  36. .rightMsg {
  37. font-size: 35rpx;
  38. color: #444;
  39. line-height: 7vw;
  40. padding: 2vw 2.5vw;
  41. background-color: #96EB6A;
  42. margin-right: -1.6vw;
  43. border-radius: 10rpx;
  44. z-index: 10;
  45. }
  46. /*向左*/
  47. .triangle_border_left {
  48. width: 0;
  49. height: 0;
  50. border-width: 10px 30px 30px 0;
  51. border-style: solid;
  52. border-color: transparent #fff transparent transparent;
  53. /*透明 黄 透明 透明 */
  54. margin: 40px auto;
  55. position: relative;
  56. }
  57. /*向右*/
  58. .triangle_border_right {
  59. width: 0;
  60. height: 0;
  61. border-width: 0px 30px 20px 13px;
  62. border-style: solid;
  63. border-color: transparent transparent transparent #96EB6A;
  64. /*透明 透明 透明 黄*/
  65. margin: 40px auto;
  66. position: relative;
  67. }

小程序配置文件代码所在路径 /pages/contact/contact.json

  1. {
  2. "navigationBarTitleText":"柯作客服",
  3. "usingComponents": {
  4. }
  5. }

小程序业务逻辑代码所在路径 /pages/contact/contact.js

  1. // pages/contact/contact.js
  2. const app = getApp();
  3. var inputVal = '';
  4. var msgList = [];
  5. var windowWidth = wx.getSystemInfoSync().windowWidth;
  6. var windowHeight = wx.getSystemInfoSync().windowHeight;
  7. var keyHeight = 0;
  8. /**
  9. * 初始化数据
  10. */
  11. function initData(that) {
  12. //输入框的内容
  13. inputVal = '';
  14. //消息列表,包含客服和用户的聊天内容
  15. msgList = [{
  16. speaker: 'server',
  17. contentType: 'text',
  18. content: 'Hi,亲爱的小主,终于等到您啦!欢迎来到柯作店铺,很荣幸为您服务。'
  19. },
  20. {
  21. speaker: 'customer',
  22. contentType: 'text',
  23. content: '你高兴的太早了'
  24. }
  25. ]
  26. that.setData({
  27. msgList,
  28. inputVal
  29. })
  30. }
  31. Page({
  32. /**
  33. * 页面的初始数据
  34. */
  35. data: {
  36. scrollHeight: '100vh',
  37. inputBottom: 0
  38. },
  39. /**
  40. * 生命周期函数--监听页面加载
  41. */
  42. onLoad: function(options) {
  43. //初始化websocket连接
  44. this.chat();
  45. //监听心跳的方法
  46. this.webSocketXin();
  47. //聊天方法
  48. initData(this);
  49. //监听消息
  50. wx.onSocketMessage(res=>{
  51. //追加到消息列表里
  52. msgList.push(JSON.parse(res.data))
  53. inputVal = '';
  54. this.setData({
  55. msgList,
  56. inputVal
  57. });
  58. })
  59. },
  60. //页面卸载时间
  61. onUnload(){
  62. wx.closeSocket();
  63. },
  64. /**
  65. * 获取聚焦
  66. */
  67. focus: function(e) {
  68. keyHeight = e.detail.height;
  69. this.setData({
  70. scrollHeight: (windowHeight - keyHeight) + 'px'
  71. });
  72. this.setData({
  73. toView: 'msg-' + (msgList.length - 1),
  74. inputBottom: keyHeight + 'px'
  75. })
  76. //计算msg高度
  77. // calScrollHeight(this, keyHeight);
  78. },
  79. //失去聚焦(软键盘消失)
  80. blur: function(e) {
  81. this.setData({
  82. scrollHeight: '100vh',
  83. inputBottom: 0
  84. })
  85. this.setData({
  86. toView: 'msg-' + (msgList.length - 1)
  87. })
  88. },
  89. /**
  90. * 发送点击监听
  91. */
  92. sendClick: function(e) {
  93. //客户发的信息
  94. let customerMsg = {
  95. uid: 10,
  96. speaker: 'customer',
  97. contentType: 'text',
  98. content: e.detail.value
  99. };
  100. //关闭心跳包
  101. this.webSocketXin(60000, false)
  102. //发送给websocket
  103. wx.sendSocketMessage({
  104. data: JSON.stringify(customerMsg),
  105. success:res=>{
  106. //重启心跳包
  107. this.webSocketXin(40000, true)
  108. }
  109. })
  110. //追加到消息列表里
  111. msgList.push(customerMsg)
  112. inputVal = '';
  113. this.setData({
  114. msgList,
  115. inputVal
  116. });
  117. },
  118. /**
  119. * 退回上一页
  120. */
  121. toBackClick: function() {
  122. wx.navigateBack({})
  123. },
  124. /**
  125. * websocket
  126. */
  127. chat(){
  128. //进行连接php的socket
  129. wx.connectSocket({
  130. //wss 协议相当于你要有一个ssl证书,https
  131. //ws 就相当于不实用证书 http
  132. url: 'ws://study.lishuo.net',
  133. success: function () {
  134. console.log('websocket连接成功~')
  135. },
  136. fail: function () {
  137. console.log('websocket连接失败~')
  138. }
  139. })
  140. },
  141. /**
  142. * 监听websocket心跳连接的方法
  143. */
  144. webSocketXin(time=60000,status=true){
  145. var timing;
  146. if(status == true){
  147. timing = setInterval(function () {
  148. console.log("当前心跳已重新连接");
  149. //循环执行代码
  150. wx.sendSocketMessage({
  151. data: JSON.stringify({
  152. type: 'active'
  153. }),
  154. fail(res) {
  155. //关闭连接
  156. wx.closeSocket();
  157. //提示
  158. wx.showToast({
  159. title: '当前聊天已断开',
  160. icon:'none'
  161. })
  162. clearInterval(timing);
  163. console.log("当前心跳已关闭");
  164. }
  165. });
  166. }, time) //循环时间,注意不要超过1分钟
  167. } else {
  168. //关闭定时器
  169. clearInterval(timing);
  170. console.log("当前心跳已关闭");
  171. }
  172. }
  173. })

2、服务端代码(PHP代码)

wechat_websocket.php

  1. <?php
  2. //创建WebSocket Server对象,监听0.0.0.0:9502端口
  3. $ws = new Swoole\WebSocket\Server('0.0.0.0', 9511);
  4. //监听WebSocket连接打开事件
  5. $ws->on('Open', function ($ws, $request) {
  6. echo $request->fd . '我连接上了';
  7. });
  8. //监听WebSocket消息事件
  9. $ws->on('Message', function ($ws, $frame) {
  10. //把前台传过来的json字符串转成数组
  11. $params = json_decode($frame->data, true);
  12. //判断是否是心跳消息,如果是心跳消息
  13. if (isset($params['type']) && isset($params['type'])=='active'){
  14. echo '这是心跳监听消息';
  15. }else{
  16. //先判断当前用户有没有正在连接
  17. if (isset($params['uid']) && !empty($params['uid'] == 666)) {
  18. //去用户表查询当前用户 fd
  19. $fd = 2;
  20. } else {
  21. $fd = 1;
  22. }
  23. //客服id
  24. $ws->push($fd, json_encode($params, JSON_UNESCAPED_UNICODE));
  25. }
  26. });
  27. //监听WebSocket连接关闭事件
  28. $ws->on('Close', function ($ws, $fd) {
  29. echo "client-{$fd} is closed\n";
  30. });
  31. $ws->start();

五、代码已经编写完了

1、把服务端代码上传到Linux操作系统里

2、然后切到该目录下进行运行php wechat_websocket.php

 总结

到此这篇关于如何利用微信小程序和php实现即时通讯聊天功能的文章就介绍到这了,更多相关微信小程序 php即时通讯聊天内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持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号