Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

javascript - Create WebSocket in Electron from main.js to index.html

I'm trying to create a WebSocket from the main.js in Electron (port 9999):

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);

Then, I want to read the message sent from the server on index.html (listening port 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>

The problem is that I'm getting the following error:

index.html:22 WebSocket connection to 'wss://localhost:9999/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

What I'm missing?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...