php+微信小程序 websocket

一、需求背景

根据需求小程序有个页面需要实时刷新数据,前端轮询太费性能,所以采用websocket。

小程序只允许xss协议,因为要https的嘛。websocket协议就是ws,https的就是wss。

二、小程序文档

wx.sendSocketMessage(Object object) | 微信开放文档

 

/(ㄒoㄒ)/~~用错了后台接收不到数据。

三、workerman

php使用tp5.0框架,原项目就是这个版本……文档里有websocket相关的。

Workerman · ThinkPHP5.0完全开发手册 · 看云

查看composer库选下版本,毕竟太老了。一般文档里有要composer安装版本的要求,最好都看下版本。

topthink/think-worker - Packagist

2.0就要求php5.1的……只能用1.0,所以命令行如下:

composer require topthink/think-worker=1.0.*
#win10 
composer require workerman/workerman-for-win

安装报错解决:

# composer版本错误 改到指定版本
composer self-update 2.1.6
# 报错 提示--no-plugin 
composer update --no-plugin


tp文档里有说明写法,不再赘述。

四、信息推送

普通信息推送直接$conn->send("str")就可以。

但这个需求里我想隔断时间就推送信息,就在onMessage()里直接用while,然后多个客户端会卡死……

后来查教程:Thinkphp5.0 安装使用Workerman实现websocket前后端通信,后端主动推送消息到前端_QQ4770851的博客-CSDN博客z

中心思想就是 在onWorkerStart()里处理,说实话我也刚学swoole,这个workerman是首次使用。

大佬们给的建议就是Timer类。

 public function onMessage($connection, $data)
    {
        $connection->send('我收到你的信息了');

        $authData = json_decode($data, true);
        $uid = $authData['uid'];
        if (!isset($connlist[$uid])) {
            $this->connlist[$uid] = $connection;
        }
        $time = time();
        $time_interval = 2; //2s
        $timer_id = Timer::add($time_interval,
            function () use ($uid) {
                var_dump($uid);
                $newtime = time();
                if (empty($this->connlist[$uid]->lasttime)) {
                    $this->connlist[$uid]->lasttime = $newtime;
                    $lasttime = $newtime;
                } else {
                    $lasttime = $this->connlist[$uid]->lasttime;
                }
                $this->connlist[$uid]->send('testtest');
                if ($newtime - $lasttime >= 60) {
                    $this->connlist[$uid]->close();
                } else {
                    $this->connlist[$uid]->lasttime = $newtime;
                }
            }
        );
    }

 事实证明大佬是对的,解决了同步堵塞问题。

五、ws反代理

wss是ws的反代理,也有详细文档。创建wss服务-workerman手册

我用的nginx,apache2半天没弄出来。

配置的时候:

 ssl_session_cache shared:SSL:50m;

 这句报错,显示配置冲突。因为其网址也用相同的域名,而这个配置是公用的,所以要一致。改成一样的就好。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lsswear

感谢大佬打赏 q(≧▽≦q)

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值