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
// 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
cmdpath 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 | undefined — undefined 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 clientsio.on(eventName, listener)— listen for server-level eventsio.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']> | undefined — undefined 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/add→controller.user.add - GET request parameters from
query, POST request parameters frombody - Paths starting with
'controller'are used directly; otherwise'controller'prefix is added automatically - URIs in
filterRequestreturn specified data directly without going through controllers
Middleware loading order:
- Error handler (
errorHandler) - Pre-middleware (
preMiddleware) - CORS cross-origin middleware
koa-bodyrequest body parsing middleware- Core routing dispatch middleware (
_dispatch) - 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:
- Remove leading
'/'from path - Check if path is in filter list (e.g.,
favicon.ico) - Ensure path starts with
'controller' - Find and call controller method via
resolveControllerFn - GET requests pass
queryparams, POST requests passbodyparams
Error handling: When controller method throws an exception, returns HTTP 500 + { error: 'Internal Server Error' }. Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| ctx | Koa.Context | Yes | Koa request context |
| next | Koa.Next | Yes | Next 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:
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:
| Parameter | Type | Required | Description |
|---|---|---|---|
| app | Koa | Yes | Koa 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
| app | Koa | Yes | Koa application instance |
| middlewares | unknown[] | No | Middleware array, defaults to [] |
| type | string | No | Type 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 viaevent.returnValue. Supports both sync and async controller methods (Electron'ssendSyncenters a nested message loop that processes microtasks). - invoke/handle model (asynchronous, recommended): Renderer uses
ipcRenderer.invoke(), main process returns a Promise viaipcMain.handle(). Supports both synchronous and asynchronous controller methods.
Channel naming rule: Replace '.' in controller path with channelSeparator (default '/'). Example: controller.user.add → controller/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
EXPORTSmarker → leaf nodes (controller method collections), callregister() - Objects without marker → intermediate nodes (directory/namespace), continue recursion Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| obj | Record<string, unknown> | Yes | Current object being traversed |
| pathname | string | Yes | Current property path |
Returns: void
IpcServer.register(exportObj, propertyChain)
Description: Register controller methods as IPC channel handlers. For each method, registers two handlers:
ipcMain.on(send/on model): Setsevent.returnValue, supports async methods. Errors are returned as{ __EE_ERROR__: true, message: string }.ipcMain.handle(invoke/handle model): Returns Promise. Errors causeipcRenderer.invoke()to reject on renderer side. Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| exportObj | Record<string, unknown> | Yes | Controller method collection object |
| propertyChain | string | Yes | Property 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:
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:
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:
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:
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:
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:
import { IoClient } from 'ee-core/socket';
const socket = IoClient('http://localhost:7070');External References
- Socket.IO official documentation: https://socket.io/
- Socket.IO Server API: https://socket.io/docs/v4/server-api/
- Koa documentation: https://koajs.com/
