1、需要一个备案域名,在宝塔可申请免费ssl证书,ssl?证书这里有个大坑,为何宝塔申请成功总是访问https失败,我发现关闭防火墙就行了。
2、开放端口,宝塔环境新开放一个端口?
nginx?配置
location /wss { ? ? ? proxy_pass http://127.0.0.1:2022; ? ? ? proxy_set_header X-Real-IP $remote_addr; ? ? ? proxy_set_header Host $host; ? ? ? proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; ? ? ? proxy_http_version 1.1; ? ? ? proxy_set_header Upgrade $http_upgrade; ? ? ? proxy_set_header Connection "upgrade"; ? ? ? rewrite /wss/(.*) /$1 break; ? ? ? proxy_redirect off; ? ? }?
3、宝塔终端启动:php server.php start -d
4、测试:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
</head>
<body>
<script>
var ws = new WebSocket("wss://www.xxx.com/wss");
ws.onopen = function() {
alert("连接成功");
ws.send('tom');
alert("给服务端发送一个字符串:tom");
};
ws.onmessage = function(e) {
alert("收到服务端的消息:" + e.data);
};
</script>
</body>
</html>
|