首页 > 解决方案 > Electron、React 和 WebSockets 导致 WebSocket.Server 不是构造函数

问题描述

我正在研究一个新项目来学习 Electron 和 React,当我尝试将 Web 套接字作为服务器启动时遇到了问题。

我有以下代码:

const WebSocket = require('ws');
        const wss = new WebSocket.Server({port: 8080});

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

            ws.send("hello");
        });

但是当我运行它时,我得到了错误:

TypeError:WebSocket.Server 不是构造函数

WS 存储库上的每个示例似乎都会引发一些奇怪的错误,并且无法找到与我正在使用的内容相关的任何内容。我正在使用来自https://github.com/websockets/ws的存储库。

更新

下面是主要流程(start.js)

const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow

const path = require('path')
const url = require('url')

let mainWindow

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

    mainWindow.loadURL(
        process.env.ELECTRON_START_URL ||
        url.format({
            pathname: path.join(__dirname, '/../public/index.html'),
            protocol: 'file:',
            slashes: true
        })
    )

    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()
    }
})

下面是渲染脚本(index.js)

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import './App.css';
import * as serviceWorker from './serviceWorker';


class StatusBar extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {
            running: false
        }
    }

    handleStartStopClick()
    {
        if (this.state.running)
        {
            this.stopProxy();
        }
        else
        {
            this.startProxy();
        }
    }

    startProxy()
    {
        const WebSocket = require('ws');
        const wss = new WebSocket.Server({port: 8080});

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

            ws.send("hello");
        });
    }

    stopProxy()
    {
        this.setState({running: false});
    }

    render() {
        let status = this.state.running ? "Stop Proxy" : "Start Proxy";
        return (

            <div className="status_bar">
                <button onClick={() => {this.handleStartStopClick()}}>
                    {status}
                </button>
            </div>
        );
    };
}

ReactDOM.render(<StatusBar />, document.getElementById("status_bar"));

标签: reactjswebsocketelectron

解决方案


您的代码在没有 Electron 的 Node.js 中运行时运行良好(前提ws是已安装该模块)。

您看到的错误可能是由提供 WebSocket 对象的两个重叠 API 引起的。看起来您正在渲染器进程中运行此代码,其中WebSocket对象已被定义为 JavaScript API 的一部分(提供 WebSocket 客户端)。

构造WebSocket.Server函数由ws模块提供,在您的情况下似乎没有加载。

如果您在渲染器进程中运行 WebSocket 服务器,请确保为相应的 BrowserWindownodeIntegration设置为。true只有这样,使用require加载 Node.js 模块才有效:

let mainWindow = new BrowserWindow( {
    width: 400,
    height: 300,
    webPreferences: {
        nodeIntegration: true
    },
});

如果你想了解 Electron 中主进程和渲染器进程之间的区别,请查看:Main and Renderer Processes


推荐阅读