gpt4 book ai didi

javascript - 有没有办法从 NativeScript 应用程序通过 SSL 与 WebSocket 通信?

转载 作者:太空宇宙 更新时间:2023-11-03 14:42:29 24 4
gpt4 key购买 nike

目前我正在编写一个 NS 应用程序,它将通过 SSL 与 WebSocket 进行通信。这是服务器的代码 (server.js):

var fs = require('fs');
var cfg = {
port: 8082,
ssl_key: fs.readFileSync('keys/server.key'),
ssl_cert: fs.readFileSync('keys/server.crt'),
ca: fs.readFileSync('keys/ca.crt')
};

var httpServ = require('https');

var WebSocketServer = require('ws').Server;
var app = null;

// dummy request processing
var processRequest = function( req, res ) {
res.writeHead(200);
res.end("All glory to WebSockets!\n");
};

app = httpServ.createServer({

// providing server with SSL key/cert
key: cfg.ssl_key,
cert: cfg.ssl_cert,
ca: cfg.ssl.ca,
passphrase: '1234',
requestCert: true,
rejectUnauthorized: false,

}, processRequest ).listen( cfg.port );

var wss = new WebSocketServer( { server: app } );

wss.on('connection', function(ws) {
console.log("Connected!");
ws.on('message', function(message) {
console.log('received: %s', message);
});
ws.send('something');
});

服务器运行良好,没有问题。下面是客户端代码(wsclient.js):

const WebSocket = require('ws');
const ws = new WebSocket('wss://localhost:8082');
ws.on('open', function open() {
ws.send("dummy");
ws.on('error', function(evt) {
console.log("The socket had an error", evt.error);
});
});

当我通过键入 node wsclient.js 运行客户端时,它抛出以下错误:

错误:无法验证第一个证书

很明显,错误是由于没有向请求提供证书信息造成的。但我不知道如何在我的客户端代码中完成这项工作。非常感谢任何线索或建议。

最佳答案

终于找到答案了:

const WebSocket = require('ws');
const ws = new WebSocket('wss://localhost:8082',{
key: fs.readFileSync('./keys/client.key'),
cert: fs.readFileSync('./keys/client.crt'),
ca: fs.readFileSync('./keys/ca.crt')
});
ws.on('open', function open() {
ws.send("dummy");
ws.on('error', function(evt) {
console.log("The socket had an error", evt.error);
});
});

现在可以了!

关于javascript - 有没有办法从 NativeScript 应用程序通过 SSL 与 WebSocket 通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42025242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com