在 Electron 中创建 WebSocket 从 main.js 到 index.html

时间:2021-01-12 09:54:45

标签: javascript node.js websocket electron

我正在尝试从 Electron(端口 9999)中的 main.js 创建一个 WebSocket:

const { app, BrowserWindow } = require('electron');
const http                   = require('http');
const WebSocket              = require('ws');
Stream                       = require('node-rtsp-stream')

require('electron-reload')();

function createWindow () {
    
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true
        }
    });

    win.loadFile('index.html');
}

function startServer () {
    
    const port = 9999;
    const server = http.createServer();
    const wss = new WebSocket.Server({ server });

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

        console.log('Llego aquí');
        ws.send('something');
        
    });
    
}

app.whenReady().then(startServer).then(createWindow);

然后,我想在index.html(侦听端口 9999)上读取服务器发送的消息:

<!DOCTYPE html>
<html>
<head>
    <meta charset = 'UTF-8'>
</head>
<body>
    <h1>App</h1>
</body>
<script>
    var exampleSocket = new WebSocket("wss://localhost:9999", "protocolOne");
    
    exampleSocket.onmessage = function (event) {
        console.log(event.data);
    }
</script>
</html>

问题是我收到以下错误:

<块引用>

index.html:22 WebSocket 连接到“wss://localhost:9999/”失败:连接建立错误:net::ERR_CONNECTION_REFUSED

我缺少什么?

0 个答案:

没有答案