Socket.IO与Electron应用程序将前端数据发送到后端?

g9icjywg  于 2023-11-15  发布在  Electron
关注(0)|答案(1)|浏览(172)

我看过很多关于如何实现socket.io的例子,但我找不到在这个过程中保持电子应用程序结构的例子(通常只是使用express)。我想知道如何用基本的电子应用程序实现socket.io?下面是我的样板代码:
Client.js文件:

const socket = io("http://localhost:3000");

// When client successfully connects to server
socket.on("connect", () => {
  console.log(`Connected to server`);
});

// Receive message from backend
socket.on("message", data => {
  console.log(`Server: ${data}`);
});

字符串
如果可能的话,我想在我的电子代码中接收上述socket.on操作(同时保留应用程序内部的东西,而不是删除应用程序代码并通过打开浏览器来执行此操作)
Electron.js样板文件:

const { app, BrowserWindow } = require('electron');
const path = require('path');

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
  // eslint-disable-line global-require
  app.quit();
}

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'));

  // Open the DevTools.
  mainWindow.webContents.openDevTools();
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

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

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});


任何帮助是赞赏!

ftf50wuq

ftf50wuq1#

我将分享我的工作示例:
Server.ts

import { Server } from "socket.io";

export interface ServerToClientEvents {
  noArg: () => void;
  basicEmit: (a: number, b: string, c: Buffer) => void;
  withAck: (d: string, callback: (e: number) => void) => void;
}

export interface ClientToServerEvents {
  hello: () => void;
}

interface InterServerEvents {
  ping: () => void;
}

interface SocketData {
  name: string;
  age: number;
}

const io = new Server<
  ClientToServerEvents,
  ServerToClientEvents,
  InterServerEvents,
  SocketData
>({
  cors: {
    origin: "http://localhost:1212"
  }
});

io.on("connection", (socket) => {
  console.log('Server received new connection');
  socket.emit("noArg");
  socket.emit("basicEmit", 1, "2", Buffer.from([3]));
  socket.emit("withAck", "4", (e) => {
    // e is inferred as number
  });

  // works when broadcast to all
  io.emit("noArg");

  // works when broadcasting to a room
  io.to("room1").emit("basicEmit", 1, "2", Buffer.from([3]));

  socket.on("hello", () => {
    console.log('Server received hello!');
  });
});

export default io;

字符串
Client.ts

import { ClientToServerEvents, ServerToClientEvents } from "main/socket";
import { io, Socket } from "socket.io-client";

// "undefined" means the URL will be computed from the `window.location` object
const URL = process.env.NODE_ENV === 'production' ? undefined : 'http://localhost:8081';

// please note that the types are reversed
export const socket: Socket<ServerToClientEvents, ClientToServerEvents> = io(URL, {
  autoConnect: false
});

socket.emit("hello");

socket.on("noArg", () => {
  // ...
});

socket.on("basicEmit", (a, b, c) => {
  // a is inferred as number, b as string and c as buffer
});

socket.on("withAck", (d, callback) => {
  // d is inferred as string and callback as a function that takes a number as argument
});

socket.connect();


并在main.ts中启动服务器

io.listen(8081);


在server.ts中,您将看到origin: "http://localhost:1212",这是CORS以避免问题警告。端口1212是在我的Electron应用程序中用作http服务器端口的数字。详细信息https://socket.io/docs/v4/handling-cors

相关问题