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

首先要申请SSL证书,必须为pem格式。

如图为宝塔环境所申请Let's Encrypt免费证书的所在位置:

Linux安装openssl支持:

yum install -y openssl


移到Swoole安装包目录,重新编译安装,并加入openssl支持:(相关文章:Linux下源码包安装Swoole及基本使用)

phpize
 
./configure --enable-openssl --with-php-config=/www/server/php/72/bin/php-config
 
make clean
 
make && make install


查看Swoole已经开启openssl支持:

php --ri swoole

Websocket服务器中开启SSL隧道,并配置证书路径:

ws_server.php:

<?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([
	'daemonize' => false, //守护进程化。
	//配置SSL证书和密钥路径
	'ssl_cert_file' => "/etc/letsencrypt/live/oyhdo.com/fullchain.pem",
	'ssl_key_file'  => "/etc/letsencrypt/live/oyhdo.com/privkey.pem"
    ]);
 
    //监听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();


页面js中即可使用wss连接WebSocket服务器(使用与证书对应的域名):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>WebSocket</title>
</head>
<body>
</body>
<script type="text/javascript">
var websocket = new WebSocket('wss://www.oyhdo.com:9501'); 
 
websocket.onopen = function (evt) { onOpen(evt) }; 
websocket.onclose = function (evt) { onClose(evt) }; 
websocket.onmessage = function (evt) { onMessage(evt) }; 
websocket.onerror = function (evt) { onError(evt) }; 
 
function onOpen(evt) {
	console.log("Connected to WebSocket server."); 
	websocket.send('666');
} 
function onClose(evt) { 
	console.log("Disconnected"); 
}
function onMessage(evt) { 
	console.log('Retrieved data from server: ' + evt.data); 
} 
function onError(evt) { 
	console.log('Error occured: ' + evt.data); 
}
</script>
</html>

启动WebSocket服务:

php ws_server.php

浏览器访问结果:(注意必须为https访问)

服务器监听结果:

posted @ 2020-01-21 10:15  码农编程进阶笔记  阅读(490)  评论(0编辑  收藏  举报
返回顶部 有事您Q我