前言
服务器: 阿里云服务器 | 需要在安全组放开443端口和workerman需要的端口
环境: oneinstack | lnmp
oneinstack添加虚拟主机的时候选择第三个即可 | 这个添加虚拟主机后面大家觉得要写个详细的或者有问题的话可以私信我
服务器端配置
workerman官方文档
http://doc.workerman.net/faq/secure-websocket-server.html
在你虚拟主机的配置文件里添加以下配置即可,利用nginx来代理wss
配置文件目录 | /usr/local/nginx/conf/vhost/
配置文件 | 域名.conf
location /wss { proxy_pass http://127.0.0.1:8282; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }
完整配置
其中xxxxxxxxx部分为域名或者证书加密字段
server { listen 443 ssl http2; ssl_certificate /usr/local/nginx/conf/ssl/xxxxxxxxxxxx.crt; ssl_certificate_key /usr/local/nginx/conf/ssl/xxxxxxxxxxxxxx.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; ssl_ciphers xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; ssl_prefer_server_ciphers on; ssl_session_timeout 10m; ssl_session_cache builtin:1000 shared:SSL:10m; ssl_buffer_size 1400; add_header Strict-Transport-Security max-age=15768000; ssl_stapling on; ssl_stapling_verify on; server_name taihaoche.ecdpower.net; access_log /data/wwwlogs/xxxxxxxxxxx_nginx.log combined; index index.html index.htm index.php; root /data/wwwroot/xxxxxxxxx/public/; if ($ssl_protocol = "") { return 301 https://$host$request_uri; } include /usr/local/nginx/conf/rewrite/thinkphp.conf; #error_page 404 /404.html; #error_page 502 /502.html; location /wss { proxy_pass http://127.0.0.1:8282; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location ~ [^/].php(/|$) { try_files $uri =404; #fastcgi_pass remote_php_ip:9000; fastcgi_pass unix:/dev/shm/php-cgi.sock; fastcgi_index index.php; include fastcgi.conf; set $real_script_name $fastcgi_script_name; if ($fastcgi_script_name ~ "^(.+?.php)(/.+)$") { set $real_script_name $1; set $path_info $2; } fastcgi_param SCRIPT_FILENAME $document_root$real_script_name; fastcgi_param SCRIPT_NAME $real_script_name; fastcgi_param PATH_INFO $path_info; } location ~ .*.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ { expires 30d; access_log off; } location ~ .*.(js|css)?$ { expires 7d; access_log off; } location ~ /.ht { deny all; } }
配置完成后不要忘记重新载入nginx,两个命令任选一个就好
service nginx reload | systemctl reload nginx
小程序端配置
xxxx代表着域名,直接是域名没有www这些东西
export let websocket_url = 'wss://xxxxxx/wss'
连接socket的方法,可参考微信小程序API中的用法 | 我使用的是mpvue框架
webSocketTask = mpvue.connectSocket({ url: websocket_url, success: function(res) { console.log(res); }, fail: function(fail) { console.log(fail); } })
有问题评论和私信都可以,推荐评论这样后面的博友有相同的问题可以直接解决~