Skip to content

Introduction

Communication service module. Provides three transport modes for controller method routing:

  • SocketServer: Socket.IO server for third-party software communication (Go, Python backends, etc.) via WebSocket
  • HttpServer: Koa-based RESTful HTTP/HTTPS server for external API calls
  • IpcServer: Electron IPC server for main ↔ renderer process communication via ipcMain/ipcRenderer

All three share the resolveControllerFn() routing mechanism. Channel pattern: controller/{name}/{method}.

Import

javascript
// CJS
const {
  SocketServer,
  HttpServer,
  IpcServer,
  loadSocket,
  createSocketServer,
  createHttpServer,
  createIpcServer,
  getSocketServer,
  getHttpServer,
  getIpcServer,
  Koa,
  IoServer,
  IoClient,
} = require('ee-core/socket');

// ESM
import {
  SocketServer,
  HttpServer,
  IpcServer,
  loadSocket,
  createSocketServer,
  createHttpServer,
  createIpcServer,
  getSocketServer,
  getHttpServer,
  getIpcServer,
  Koa,
  IoServer,
  IoClient,
} from 'ee-core/socket';

SocketServer

Socket.IO server. Provides WebSocket/HTTP polling communication for third-party software (non-Electron renderer processes) to call main process controller methods.

Communication protocol:

  • Client connects and sends messages on a specified channel: { cmd: 'controller/user/add', args: {...} }
  • Server parses the cmd path and calls the corresponding controller method
  • Controller execution result is returned to client via callback

Created using factory pattern (static create()) because initialization requires async port acquisition. When enable=false in config, the service will not start after creation.

SocketServer.create()

Description: Factory method — create and initialize a SocketServer instance. Acquires an available port, creates a Socket.IO Server instance, and sets up connection listeners. The port number is written to process.env.EE_SOCKET_PORT for other modules to access. Returns: Promise<SocketServer> — fully initialized SocketServer instance.

SocketServer.init()

Description: Initialize the Socket.IO server. If config.enable === false, returns immediately without starting. Otherwise acquires a port, creates the Socket.IO Server, and calls connect(). Returns: Promise<void>

SocketServer.connect()

Description: Listen for client connections and handle messages. After a client connects, listens on the configured channel (default 'socket-channel'). Upon receiving a message, routes via cmd path to the corresponding controller method. Results are sent back to client via callback. Errors are returned as { __EE_ERROR__: true, message: string }. Returns: void

SocketServer.io

Description: The instantiated Socket.IO Server object. Type: Server | undefinedundefined before initialization or when enable=false.

Properties and methods follow the Socket.IO Server API: https://socket.io/docs/v4/server-api/

Key methods:

  • io.emit(eventName[, ...args]) — broadcast to all connected clients
  • io.on(eventName, listener) — listen for server-level events
  • io.close([callback]) — close the server

SocketServer.socket

Description: The socket object established through io.on('connection'). Represents the currently connected client socket instance. Type: ReturnType<Server['on']> | undefinedundefined until a client connects.

Socket.IO Socket API: https://socket.io/docs/v4/server-api#socket

SocketServer.config

Description: Socket.IO server configuration object. Type: SocketServerConfig — contains enable, port, path, channel, cors, transports, etc.

SocketServer.channelSeparator

Description: Channel separator used for controller path routing. Type: string — defaults to '/'.

HttpServer

Koa-based HTTP/HTTPS server. Provides RESTful API services, routing HTTP requests to corresponding controller methods.

Request routing rules:

  • URL path maps to controller path, e.g., /controller/user/addcontroller.user.add
  • GET request parameters from query, POST request parameters from body
  • Paths starting with 'controller' are used directly; otherwise 'controller' prefix is added automatically
  • URIs in filterRequest return specified data directly without going through controllers

Middleware loading order:

  1. Error handler (errorHandler)
  2. Pre-middleware (preMiddleware)
  3. CORS cross-origin middleware
  4. koa-body request body parsing middleware
  5. Core routing dispatch middleware (_dispatch)
  6. Post-middleware (postMiddleware)

Created using factory pattern (static create()). When enable=false in config, the service will not start after creation.

HttpServer.create()

Description: Factory method — create and initialize an HttpServer instance. Acquires an available port, creates a Koa application with middleware, and starts HTTP/HTTPS listening. The port number is written to process.env.EE_HTTP_PORT for other modules to access. Returns: Promise<HttpServer> — fully initialized HttpServer instance.

HttpServer.init()

Description: Initialize the HTTP server. If config.enable === false, returns immediately. Otherwise acquires a port and calls _create(). Returns: Promise<void>

HttpServer._create()

Description: Create the Koa application and start HTTP/HTTPS service. Loads middleware in order, handles HTTPS/SSL configuration, and starts listening on the configured host and port. Returns: Promise<void>

HttpServer._dispatch(ctx, next)

Description: Core routing dispatch middleware. Maps HTTP request paths to controller methods:

  1. Remove leading '/' from path
  2. Check if path is in filter list (e.g., favicon.ico)
  3. Ensure path starts with 'controller'
  4. Find and call controller method via resolveControllerFn
  5. GET requests pass query params, POST requests pass body params

Error handling: When controller method throws an exception, returns HTTP 500 + { error: 'Internal Server Error' }. Parameters:

ParameterTypeRequiredDescription
ctxKoa.ContextYesKoa request context
nextKoa.NextYesNext middleware function

Returns: Promise<void>

HttpServer.getHttpApp()

Description: Get the Koa application instance. Returns: Koa | undefined — Koa instance, or undefined if HTTP service is not enabled. Example:

javascript
import { getHttpServer } from 'ee-core/socket';
const httpApp = getHttpServer().getHttpApp();

HttpServer._setupErrorHandler(app, errorHandler)

Description: Set up Koa error handler. Registers the provided function as a Koa 'error' event listener. Parameters:

ParameterTypeRequiredDescription
appKoaYesKoa application instance
errorHandler`((err: Error) => void)null`Yes

Returns: void

HttpServer._loadMiddlewares(app, middlewares, type)

Description: Load pre/post middleware. Middleware can be factory functions (called to return Koa middleware) or direct middleware functions. Invalid middleware will be skipped with a warning. Parameters:

ParameterTypeRequiredDescription
appKoaYesKoa application instance
middlewaresunknown[]NoMiddleware array, defaults to []
typestringNoType identifier ('pre' or 'post'), defaults to 'pre'

Returns: void

HttpServer.config

Description: HTTP server configuration object. Type: HttpServerConfig — contains enable, port, host, protocol, https, cors, body, filterRequest, koaConfig, etc.

HttpServer.channelSeparator

Description: Channel separator used for controller path routing. Type: string — defaults to '/'.

IpcServer

Electron IPC server. Registers controller methods as ipcMain channel handlers, enabling renderer processes to call main process controller methods via ipcRenderer.

Supports two communication models:

  • send/on model (synchronous): Renderer uses ipcRenderer.sendSync(), main process returns results via event.returnValue. Supports both sync and async controller methods (Electron's sendSync enters a nested message loop that processes microtasks).
  • invoke/handle model (asynchronous, recommended): Renderer uses ipcRenderer.invoke(), main process returns a Promise via ipcMain.handle(). Supports both synchronous and asynchronous controller methods.

Channel naming rule: Replace '.' in controller path with channelSeparator (default '/'). Example: controller.user.addcontroller/user/add.

IpcServer.constructor()

Description: Create and initialize an IpcServer instance. Reads channelSeparator from config, then traverses the controller object tree and registers all IPC channels. Returns: IpcServer — initialized instance.

IpcServer.init()

Description: Initialize — traverse controller tree and register all IPC channel handlers. Called automatically by the constructor. Returns: void

IpcServer.loop(obj, pathname)

Description: Recursively traverse the controller object tree. Distinguished by EXPORTS symbol marker:

  • Objects with EXPORTS marker → leaf nodes (controller method collections), call register()
  • Objects without marker → intermediate nodes (directory/namespace), continue recursion Parameters:
ParameterTypeRequiredDescription
objRecord<string, unknown>YesCurrent object being traversed
pathnamestringYesCurrent property path

Returns: void

IpcServer.register(exportObj, propertyChain)

Description: Register controller methods as IPC channel handlers. For each method, registers two handlers:

  1. ipcMain.on (send/on model): Sets event.returnValue, supports async methods. Errors are returned as { __EE_ERROR__: true, message: string }.
  2. ipcMain.handle (invoke/handle model): Returns Promise. Errors cause ipcRenderer.invoke() to reject on renderer side. Parameters:
ParameterTypeRequiredDescription
exportObjRecord<string, unknown>YesController method collection object
propertyChainstringYesProperty path (e.g., 'controller.user')

Returns: void

IpcServer.channelSeparator

Description: Channel separator used for IPC channel name generation. Type: string — defaults to '/'.

IpcServer.directory

Description: Controller directory name, used as the property path prefix. Type: string'controller'.

Factory Functions

Module-level functions that create, retrieve, and initialize communication service instances.

loadSocket()

Description: Load and initialize all communication services. Created in order: SocketServer → HttpServer → IpcServer. Called by Application.run() during the framework startup flow. Returns: Promise<void>See also: ps module — getSocketPort() / getHttpPort() return the ports set during this initialization.

createSocketServer()

Description: Create a SocketServer instance via SocketServer.create() and store it in the module instance registry. Returns: Promise<SocketServer> — the created SocketServer instance.

createHttpServer()

Description: Create an HttpServer instance via HttpServer.create() and store it in the module instance registry. Returns: Promise<HttpServer> — the created HttpServer instance.

createIpcServer()

Description: Create an IpcServer instance and store it in the module instance registry. Unlike SocketServer and HttpServer, IpcServer creation is synchronous. Returns: IpcServer — the created IpcServer instance.

getSocketServer()

Description: Get the SocketServer instance. Throws Error if called before the Ready lifecycle event (i.e., before createSocketServer() has been called). Returns: SocketServer — the stored SocketServer instance (non-null). Example:

javascript
import { getSocketServer } from 'ee-core/socket';
const server = getSocketServer();
server.io.emit('channel-name', 'data');

TIP

Changed from v5: getSocketServer() returns SocketServer (not SocketServer | null). Throws Error if called before services are created.

getHttpServer()

Description: Get the HttpServer instance. Throws Error if called before the Ready lifecycle event (i.e., before createHttpServer() has been called). Returns: HttpServer — the stored HttpServer instance (non-null). Example:

javascript
import { getHttpServer } from 'ee-core/socket';
const httpApp = getHttpServer().getHttpApp();

TIP

Changed from v5: getHttpServer() returns HttpServer (not HttpServer | null).

getIpcServer()

Description: Get the IpcServer instance. Throws Error if called before the Ready lifecycle event (i.e., before createIpcServer() has been called). Returns: IpcServer — the stored IpcServer instance (non-null). Example:

javascript
import { getIpcServer } from 'ee-core/socket';
const ipc = getIpcServer();

TIP

Changed from v5: getIpcServer() returns IpcServer (not IpcServer | null).

Re-exported Libraries

The socket module re-exports underlying library classes for direct use in application code.

Koa

Description: The original Koa class (import Koa from 'koa'), re-exported for convenience. Use when adding custom middleware or extending the HTTP server. Returns: Koa class (the constructor function). Example:

javascript
import { Koa } from 'ee-core/socket';
const app = new Koa();

IoServer

Description: The original Socket.IO Server class (import { Server } from 'socket.io'), re-exported for convenience. Use when creating additional Socket.IO instances. Returns: Server class from socket.io. Example:

javascript
import { IoServer } from 'ee-core/socket';

IoClient

Description: The original Socket.IO client module (import IoClient from 'socket.io-client'), re-exported for convenience. Use when connecting to the Socket.IO server from external processes. Returns: socket.io-client module. Example:

javascript
import { IoClient } from 'ee-core/socket';
const socket = IoClient('http://localhost:7070');

External References