如何利用微信小程序和php实现即时通讯聊天功能

2022-04-18 16:19:10
目录
一、php7安装Swoole扩展1、自定义安装2、宝塔面板安装PHP swoole扩展二、配置nginx反向代理三、微信小程序socket合法域名配置四、效果演示和代码1、小程序端代码2、服务端代码(PHP代码)五、代码已经编写完了 总结

一、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、自定义安装

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

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

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

x; z-index: 10;} /*向左*/ .triangle_border_left { width: 0; height: 0; border-width:易采站长站 10px 30px 30px 0; border-style: solid; border-color: transparent #fff transparent transparent; /*透明 黄 透明 透明 */ margin: 40px auto; position: relative;} /*向右*/ .triangle_border_right { width: 0; height: 0; border-width: 0px 30px 20px 13px; border-style: solid; border-color: transparent transparent transparent #96EB6A; /*透明 透明 透明 黄*/ margin: 40px auto; position: relative; }

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

{  "navigationBarTitleText":"柯作客服",  "usingComponents": {    }}

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

// pages/contact/contact.jsconst app = getApp();var inputVal = '';var msgList = [];var windowWidth = wx.getSystemInfoSync().windowWidth;var windowHeight = wx.getSystemInfoSync().windowHeight;var keyHeight = 0; /** * 初始化数据 */function initData(that) {  //输入框的内容  inputVal = '';  //消息列表,包含客服和用户的聊天内容  msgList = [{      speaker: 'server',      contentType: 'text',      content: 'Hi,亲爱的小主,终于等到您啦!欢迎来到柯作店铺,很荣幸为您服务。'    },    {      speaker: 'customer',      contentType: 'text',      content: '你高兴的太早了'    }  ]  that.setData({    msgList,    inputVal  })} Page({  /**   * 页面的初始数据   */  data: {    scrollHeight: '100vh',    inputBottom: 0  },   /**   * 生命周期函数--监听页面加载   */  onLoad: function(options) {    //初始化websocket连接    this.chat();    //监听心跳的方法    this.webSocketXin();    //聊天方法    initData(this);     //监听消息    wx.onSocketMessage(res=>{         //追加到消息列表里        msgList.push(JSON.parse(res.data))        inputVal = '';        this.setData({          msgList,          inputVal        });    })    },  //页面卸载时间  onUnload(){    wx.closeSocket();  },  /**   * 获取聚焦   */  focus: function(e) {    keyHeight = e.detail.height;    this.setData({      scrollHeight: (windowHeight - keyHeight) + 'px'    });    this.setData({      toView: 'msg-' + (msgList.length - 1),      inputBottom: keyHeight + 'px'    })    //计算msg高度    // calScrollHeight(this, keyHeight);   },   //失去聚焦(软键盘消失)  blur: function(e) {    this.setData({      scrollHeight: '100vh',      inputBottom: 0    })    this.setData({      toView: 'msg-' + (msgList.length - 1)    })  },   /**   * 发送点击监听   */  sendClick: function(e) {    //客户发的信息    let customerMsg = {      uid: 10,      speaker: 'customer',      contentType: 'text',      content: e.detail.value    };      //关闭心跳包     this.webSocketXin(60000, false)    //发送给websocket    wx.sendSocketMessage({      data: JSON.stringify(customerMsg),      success:res=>{        //重启心跳包        this.webSocketXin(40000, true)      }      })     //追加到消息列表里    msgList.push(customerMsg)    inputVal = '';    this.setData({      msgList,      inputVal    });  },  /**   * 退回上一页   */  toBackClick: function() {    wx.navigateBack({})  },  /**   * websocket   */  chat(){     //进行连接php的socket     wx.connectSocket({       //wss 协议相当于你要有一个ssl证书,https       //ws  就相当于不实用证书  http      url: 'ws://study.lishuo.net',      success: function () {        console.log('websocket连接成功~')      },      fail: function () {        console.log('websocket连接失败~')      }    })  },    /**   * 监听websocket心跳连接的方法   */  webSocketXin(time=60000,status=true){    var timing;    if(status == true){      timing = setInterval(function () {        console.log("当前心跳已重新连接");        //循环执行代码        wx.sendSocketMessage({          data: JSON.stringify({            type: 'active'          }),          fail(res) {            //关闭连接            wx.closeSocket();            //提示            wx.showToast({              title: '当前聊天已断开',              icon:'none'            })            clearInterval(timing);            console.log("当前心跳已关闭");          }        });      }, time) //循环时间,注意不要超过1分钟      } else {      //关闭定时器      clearInterval(timing);      console.log("当前心跳已关闭");    }     }   })

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

wechat_websocket.php

<?php //创建WebSocket Server对象,监听0.0.0.0:9502端口$ws = new SwooleWebSocketServer('0.0.0.0', 9511); //监听WebSocket连接打开事件$ws->on('Open', function ($ws, $request) {    echo $request->fd . '我连接上了';}); //监听WebSocket消息事件$ws->on('Message', function ($ws, $frame) {    //把前台传过来的json字符串转成数组    $params = json_decode($frame->data, true);    //判断是否是心跳消息,如果是心跳消息    if (isset($params['type']) && isset($params['type'])=='active'){        echo '这是心跳监听消息';    }else{        //先判断当前用户有没有正在连接        if (isset($params['uid']) && !empty($params['uid'] == 666)) {            //去用户表查询当前用户  fd            $fd = 2;        } else {            $fd = 1;        }        //客服id        $ws->push($fd, json_encode($params, JSON_UNESCAPED_UNICODE));    }}); //监听WebSocket连接关闭事件$ws->on('Close', function ($ws, $fd) {    echo "client-{$fd} is closedn";}); $ws->start();

五、代码已经编写完了

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

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

如何利用微信小程序和php实现即时通讯聊天功能

 总结

相关文章 大家在看