无法从 JavaScript 客户端通过 https 连接到 websocket 服务器 [英] Unable to connect to websocket server over https from JavaScript client

查看:28
本文介绍了无法从 JavaScript 客户端通过 https 连接到 websocket 服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码为我的 webrtc 应用程序创建了 websocket 服务器

I have created websocket server for my webrtc app using the following code

 const https = require('https');
const fs = require('fs');

const options = {
    key: fs.readFileSync('C:/.../key_store.key'),
    cert: fs.readFileSync('C:/.../key_store.crt')
};

var server = https.createServer(options, (req, res) => { res.writeHead(200); res.end('hello world\n');}).listen(9090);



//require our websocket library
var WebSocketServer = require('ws').Server;

//creating a websocket server at port 9090 
var wss = new WebSocketServer({server});

我的 websocket 客户端代码是:

My websocket client code is :

conn = new WebSocket('ws://localhost:9090');

当我尝试使用上述代码连接到 websocket 服务器时,我在 JavaScript 控制台中收到以下异常:

I am getting the following exception in JavaScript console when I am trying to connect to websocket server using the above code:

VM908:35 与ws://localhost:9090/"的 WebSocket 连接失败:在收到握手响应之前连接已关闭

VM908:35 WebSocket connection to 'ws://localhost:9090/' failed: Connection closed before receiving a handshake response

我尝试在 chrome 中导入证书,但没有成功.

I tried importing certificates in chrome but with no success.

推荐答案

WebRTC 要求 https 和 https 页面仅允许安全 Wecsockets (wss) 连接.

WebRTC requires https and https pages allow Secure Wecsockets (wss) connections only.

所以需要在客户端创建WebSocket如下

So you need to create WebSocket in the client side as follows

conn = new WebSocket("wss://your_server_ip:wss_port/");
In your case:
conn = new WebSocket("wss://139.126.123.18:9090/");

我认为您在 WebSocket 服务器中使用了自签名 SSL 证书(key_store.crt/.key).
在这种情况下,浏览器将为这些连接引发 ERR_INSECURE_RESPONSE 异常.
因此,我们通过在浏览器中访问该 url 来手动添加异常,如下所示.

I think you are using self signed SSL certificates(key_store.crt/.key) in your WebSocket Server.
In that case browsers will raise ERR_INSECURE_RESPONSE exception for those connections.
So we have add exception manually by accessing that url in browser as following.

在新标签页中打开 https://139.126.123.18:9090/
然后点击高级 -> 继续(对于 Chrome).

Open https://139.126.123.18:9090/ in new tab,
Then click on Advanced -> proceed (for Chrome).

或者您可以将自签名 CA 导出到浏览器.

Or you can export your self signed CA to browsers.

现在您的安全 WebSocket 应该已连接.

Now your Secure WebSocket should get connected.

这篇关于无法从 JavaScript 客户端通过 https 连接到 websocket 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆