Lnmp Swoole使用wss协议

image.png

准备工作

申请 SSL 证书,传送 阿里云免费SSL证书申请
首先安装 swoole 扩展,传送 Lnmp Swoole扩展安装

开启SSL支持

  • 安装openssl
1
$ apt install openssl
  • 进入 swoole 安装包目录
1
$ cd swoole-1.7.21
  • 运行 phpize
1
$ /usr/bin/phpize
  • 重新编译安装,并加入 openssl 支持
1
$ ./configure --enable-openssl --with-php-config=/usr/bin/php-config
  • 清除临时文件
1
$ make clean

清除上次的 make 命令所产生的 object 文件(后缀为“.o”的文件)及可执行文件。

  • 构建并安装
1
$ make && make install
  • 查看 swoole 是否已经开启 openssl 支持
1
2
$ php --ri swoole | grep openssl
openssl => enabled

搭建WebSocket服务端

  • 创建 server.php,代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
//创建websocket服务器对象,监听0.0.0.0:9501端口,开启SSL隧道
$ws = new swoole_websocket_server("0.0.0.0", 9501, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);

//配置参数
$ws ->set([
'max_conn'=>1000,
'task_worker_num' => 2,
'daemonize' => false, //守护进程化。
//配置SSL证书和密钥路径
'ssl_cert_file' => "/etc/nginx/cert/socket.yuhal.com.pem",
'ssl_key_file' => "/etc/nginx/cert/socket.yuhal.com.key"
]);

//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
echo "client-{$request->fd} is open\n";
});

//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
echo "Message: {$frame->data}\n";
$ws->push($frame->fd, "server: {$frame->data}");
});

//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});

$ws->start();
  • 启动 WebSocket 服务
1
$ php server.php

测试使用wss协议

传送 WEBSOCKET 在线测试工具

image.png

-------------本文结束感谢您的阅读-------------
0%