SimulatedGREG / electron-vue

An Electron & Vue.js quick start boilerplate with vue-cli scaffolding, common Vue plugins, electron-packager/electron-builder, unit/e2e testing, vue-devtools, and webpack.
https://simulatedgreg.gitbooks.io/electron-vue/content/
MIT License
15.48k stars 1.55k forks source link

can't use webscoket in server #965

Closed StringKe closed 4 years ago

StringKe commented 4 years ago

Found an issue or bug with electron-vue? Tell me all about it!

Questions regarding how to use electron or vue are likely to be closed as they are not direct issues with this boilerplate. Please seek solutions from official documentation or their respective communities.

Describe the issue / bug.

Starting websocket before randerer and server can be started under develop, but cannot build

How can I reproduce this problem?
import ws from 'ws';
import http from 'http';
import notify from './notify';

class Server {
  webSocketServer = null;
  webSocketLoop = null;
  checkController = undefined;

  Start() {
    const httpServer = http.createServer((req, res) => {
      req.on('error', error => notify.errorMessage('HTTP Request 服务错误', error));
      res.on('error', error => notify.errorMessage('HTTP Response 服务错误', error));
      res.end();
    })
      .on('error', error => notify.errorMessage('HTTP 服务错误', error));

    httpServer.listen(7891, '0.0.0.0', () => {
      this.wsServer(httpServer);
      notify.logMessage('启动成功,监听正常', {});
    });

    setInterval(() => {
      notify.logMessage('123123');
    }, 1000);
  }

  wsServer(httpServer) {
    const webSocketsOptions = {
      server: httpServer,
    };
    this.webSocketServer = new ws.Server(webSocketsOptions);

    this.webSocketServer
      .on('error', error => notify.log('websocket', error))
      .on('connection', (_client, req) => {
        const remoteAddress = req.headers['x-real-ip'] === undefined
          ? `${req.connection.remoteAddress}:${req.connection.remotePort}`
          : `${req.headers['x-real-ip']}:${req.headers['x-real-port']}`;
        this.controller(_client, remoteAddress);
        notify.logMessage(`地址 => ${remoteAddress} 状态 => 已经链接`);
      });
    this.webSocketLoop = setInterval(() => this.webSocketPing(), 60 * 1000);
  }

  controller(client, remoteAddress) {
    if (this.checkController !== undefined) {
      this.checkController.close(1001, '太多链接,无法处理');
    }
    const onLog = data => this.sendMessage(data);
    client
      .on('error', (err) => {
        notify.removeListener('log', onLog);
        this.destroyClient(client);
        notify.error(client.protocol, remoteAddress, err);
      })
      .on('close', (code, reason) => {
        notify.removeListener('log', onLog);
        this.destroyClient(client);
        notify.waringMessage(`地址: ${remoteAddress} 已断开`, {
          code,
          reason,
        });
      })
      .on('message', async (msg) => {
        const message = await JSON.parse(msg);
        if (message !== undefined && message.cmd !== undefined && message.ts !== undefined) {
          this.pcsCommand(message);
        }
      });
    this.checkController = client;
    notify.on('log', onLog);
  }

  pcsCommand(message) {
    const { cmd, ts } = message;
    this.sendMessage({
      cmd,
      ts,
      msg: '未知命令',
    });
  }

  sendMessage(data) {
    if (this.checkController.readyState === ws.OPEN) {
      this.checkController.send(JSON.stringify(data));
    }
  }

  // eslint-disable-next-line class-methods-use-this
  destroyClient(client) {
    client.close();
    client.terminate();
    client.removeAllListeners();
  }

  webSocketPing() {
    this.webSocketServer.clients.forEach(client => client.ping());
  }
}

export default Server;

src/main/index.js

import { app, BrowserWindow } from 'electron' // eslint-disable-line
import Server from './server/index';
/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\') // eslint-disable-line
}

const server = new Server();
server.Start();

let mainWindow;
const winURL = process.env.NODE_ENV === 'development'
  ? 'http://localhost:9080'
  : `file://${__dirname}/index.html`;

function createWindow() {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    height: 563,
    useContentSize: true,
    width: 1000,
  });

  mainWindow.loadURL(winURL);

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow();
  }
});
If visual, provide a screenshot.

image

Tell me about your development environment.

If you are looking to suggest an enhancement or feature, then feel free to remove everything above.

NoelDavies commented 4 years ago

I'm using socket.io and mine works fine? What's in Server/index