以本地链接线上websocket为例,如图所示
var ws = new WebSocket("ws://127.0.0.1:6543");
ws.onopen = function()
{
ws.send(JSON.stringify({'type':'bind','uid':1}))
};
步骤一:如果请求域名为http,则可以正常访问,然而当域名为https时,就会报错,如下图所示
错误信息:Mixed Content: The page at ‘https://{域名}.com/‘ was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint ‘ws://{ip}:{port}/‘. This request has been blocked; this endpoint must be available over WSS.
Uncaught DOMException: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS
步骤二:根据错误提示信息,需要使用wss请求var ws = new WebSocket("wss://127.0.0.1:6543");
这时重新访问,会出现如下图所示信息
错误信息:failed:Error in connection establishment: newt::ERR_SSLPROTOCOL_ERROR
注:在使用https协议时,需要指定域名,这里换成ws = new WebSocket("wss://{域名}/wss");
同时修改nginx配置文件,在conf中加入以下代码
location /wss {
proxy_pass http://172.30.9.176:6543;
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";
}
重启nginx服务后即可正常通讯