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

发布于 2025-01-10 19:29:04 字数 1595 浏览 0 评论 0原文

我看过很多关于如何实现 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();
  }
});

感谢任何帮助!

I've seen a lot of examples on how to implement socket.io, but none that I can find that maintain the structure of the electron app in the process (typically it's just using express instead). I was wondering how I could implement socket.io with a basic electron app? Here's my boiler plate code:

Client.js file:

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

I'd like to receive the above socket.on actions in my electron code if possible (while keeping things inside the app as opposed removing the app code and doing this by opening the browser)

Electron.js boilerplate:

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

Any help is appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

狼亦尘 2025-01-17 19:29:04

我将分享我的工作示例:

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

I will share my working example:

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

And started server in main.ts

  io.listen(8081);

In server.ts you will see origin: "http://localhost:1212" this is CORS to avoid issues warnings. Port 1212 is number that is used in my Electron app as http server port. Details https://socket.io/docs/v4/handling-cors

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文