连接建立中的WebSocket错误:net :: ERR_CONNECTION_CLOSED

crm*_*ham 10 apache https wss websocket node.js

我尝试wss与服务器建立连接时收到此错误:

与'wss:// mydomain:3000 /'的WebSocket连接失败:连接建立错误:net :: ERR_CONNECTION_CLOSED

我目前有一个apache2虚拟主机配置设置来监听端口443和80上的请求:

<VirtualHost *:80>
        ServerName otherdomainname.co.uk
        ServerAlias www.otherdomainname.co.uk

        RewriteEngine On
        RewriteRule ^/(.*)$ /app/$1 [l,PT]

        JkMount /* worker2

</VirtualHost>

<VirtualHost _default_:443>
        ServerName otherdomainname.co.uk
        ServerAlias www.otherdomainname.co.uk

        RewriteEngine On
        RewriteRule ^/(.*)$ /app/$1 [l,PT]

        SSLEngine On
        SSLCertificateFile /etc/apache2/ssl/apache.crt
        SSLCertificateKeyFile /etc/apache2/ssl/apache.key

        <Location />
        SSLRequireSSL On
        SSLVerifyClient optional
        SSLVerifyDepth 1
        SSLOptions +StdEnvVars +StrictRequire
        </Location>

        JkMount /* worker2

</VirtualHost>
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,它使用JkMount将请求传递给Tomcat,后者在HTTP和HTTPS上正确地提供网页.

当我在端口80上使用HTTP协议访问站点时,可以使用该协议建立WebSocket连接ws.

当我在端口443上使用HTTPS协议访问该站点时,该站点正确提供但未使用WebSocket连接wss.

我使用"ws"node.js模块来提供WebSocket服务器:

var WebSocketServer = require('ws').Server
  , wss = new WebSocketServer({ port: 3000 }),
  fs = require('fs');

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);

    ws.send(message);
  ws.send('something');
});
Run Code Online (Sandbox Code Playgroud)

为什么我无法使用wss协议成功连接到WebSocket服务器https

crm*_*ham 12

问题是我没有为https/wss配置WebSocket服务器.

这是我的不安全的WebSocket服务器的安全版本,使用来自node.js的"ws".

var WebSocketServer = require('ws').Server,
  fs = require('fs');


var cfg = {
        ssl: true,
        port: 3000,
        ssl_key: '/path/to/apache.key',
        ssl_cert: '/path/to/apache.crt'
    };

var httpServ = ( cfg.ssl ) ? require('https') : require('http');

var app      = null;

var processRequest = function( req, res ) {

    res.writeHead(200);
    res.end("All glory to WebSockets!\n");
};

if ( cfg.ssl ) {

    app = httpServ.createServer({

        // providing server with  SSL key/cert
        key: fs.readFileSync( cfg.ssl_key ),
        cert: fs.readFileSync( cfg.ssl_cert )

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

} else {

    app = httpServ.createServer( processRequest ).listen( cfg.port );
}

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

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);

    ws.send(message);

  });

  ws.send('something');
});
Run Code Online (Sandbox Code Playgroud)