首页 > 解决方案 > 您如何在电子中使用 socket.io?

问题描述

我正在尝试在电子应用程序中实现 socket.io。按照之前关于一个问题的建议,我遵循了这个聊天应用程序示例https://socket.io/get-started/chat/,然后尝试将其变成一个电子应用程序。但是现在好像功能不存在,我做错了什么?该应用程序启动,但我只看到我可以输入和提交的前端,但什么也没有回来。代码如下

main.js

    const { app, BrowserWindow } = require('electron')
    
    function createWindow () {
      const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true
        }
      })
    
      win.loadFile('index.html')
    }
    
    app.whenReady().then(createWindow)
    
    app.on('window-all-closed', () => {
      if (process.platform !== 'darwin') {
        app.quit()
      }
    })
    
    app.on('activate', () => {
      if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
      }
    })

index.js

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
    console.log('a user connected');
    socket.on('chat message', (msg) => {
        io.emit('chat message', msg)
    });
});

索引.html

    <ul id="messages"></ul>
    <form id="form" action="">
        <input id="input" autocomplete="off" /><button>Send</button>
    </form>

    <script src="/socket.io/socket.io.js"></script>
    <script>
        var socket = io();

        var messages = document.getElementById('messages');
        var form = document.getElementById('form');
        var input = document.getElementById('input');

        form.addEventListener('submit', function (e) {
            e.preventDefault();
            if (input.value) {
                socket.emit('chat message', input.value);
                input.value = '';
            }
        });

        socket.on('chat message', function (msg) {
            var item = document.createElement('li');
            item.textContent = msg;
            messages.appendChild(item);
            window.scrollTo(0, document.body.scrollHeight);
        });
    </script>

</body>

如果我使用 node index.js 它可以完美运行(我在这个问题中使用了端口 3000 的监听)但是 npm start 用作电子应用程序没有。请帮忙!!!!!

标签: node.jssocket.ioelectron

解决方案


推荐阅读