ThinkPHP5.0的think-swoole 开启WebSocket的SSL支持 使用wss连接

相关文章:ThinkPHP5.0结合Swoole开发WebSocket在线聊天

                  Swoole WebSocket开启SSL支持 使用wss连接

找到think-swoole的Server.php:

在构造方法中增加一个WebSocket服务类型,调用mode和sockType参数:

case 'ssl':
     $this->swoole = new Websocket($this->host, $this->port, $this->mode, $this->sockType);
break;

 

 控制器中配置serverType 、mode和sockType三个参数:

<?php
 
namespace app\home\controller;
use think\swoole\Server;
class WebSocket extends Server
{
    protected $host = '0.0.0.0'; //监听所有地址
    protected $port = 9501; //监听9501端口
    
    protected $serverType = 'ssl';
    protected $mode = SWOOLE_PROCESS;
    protected $sockType = SWOOLE_SOCK_TCP | SWOOLE_SSL;

    protected $option = [ 
        'worker_num'=> 4, //设置启动的Worker进程数
        'daemonize'	=> false, //守护进程化(上线改为true)
        'backlog'	=> 128, //Listen队列长度
        'dispatch_mode' => 2, //固定模式,保证同一个连接发来的数据只会被同一个worker处理
 
        //心跳检测:每60秒遍历所有连接,强制关闭10分钟内没有向服务器发送任何数据的连接
        'heartbeat_check_interval' => 60,
        'heartbeat_idle_time' => 600
    ];
 
    //建立连接时回调函数
    public function onOpen($server,$req)
    {
        echo "标识{$req->fd}建立了连接\n";
    }
 
    //接收数据时回调函数
    public function onMessage($server,$frame)
    {

    }
 
    //连接关闭时回调函数
    public function onClose($server,$fd)
    {
        echo "标识{$fd}关闭了连接\n";
    }
}

然后前端js就可以使用wss访问WebSocket服务了(客户端必须为https访问)

发布了103 篇原创文章 · 获赞 167 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/msllws/article/details/84875121