@push.rocks/smartsocket
Provides easy and secure websocket communication mechanisms, including server and client implementation, function call routing, connection management, and tagging.
readme.md for @push.rocks/smartsocket
Easy and secure WebSocket communication with native WebSocket support π
Features
- π Native WebSocket - Uses native WebSocket API (browser) and
wslibrary (Node.js) - π Auto Reconnection - Exponential backoff with configurable retry limits
- π‘ RPC-style Function Calls - Define and call functions across server/client
- π·οΈ Connection Tagging - Tag connections for easy identification and routing
- π Smartserve Integration - Works seamlessly with
@push.rocks/smartserve - π Secure Communication - WSS support for encrypted connections
Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly.
Install
npm install @push.rocks/smartsocket --save
or with pnpm:
pnpm add @push.rocks/smartsocket
Usage
Quick Start - Server
import { Smartsocket, SocketFunction } from '@push.rocks/smartsocket';
// Create server
const server = new Smartsocket({
alias: 'myServer',
port: 3000
});
// Define a function that clients can call
const greetFunction = new SocketFunction({
funcName: 'greet',
funcDef: async (data, socketConnection) => {
console.log(`Received greeting from ${data.name}`);
return { message: `Hello, ${data.name}!` };
}
});
server.addSocketFunction(greetFunction);
// Start the server
await server.start();
console.log('WebSocket server running on port 3000');
Quick Start - Client
import { SmartsocketClient } from '@push.rocks/smartsocket';
// Create client
const client = new SmartsocketClient({
url: 'http://localhost',
port: 3000,
alias: 'myClient',
autoReconnect: true
});
// Connect to server
await client.connect();
// Call server function
const response = await client.serverCall('greet', { name: 'Alice' });
console.log(response.message); // "Hello, Alice!"
Connection Options
The SmartsocketClient supports several configuration options:
const client = new SmartsocketClient({
url: 'http://localhost', // Server URL (http/https)
port: 3000, // Server port
alias: 'myClient', // Client identifier
autoReconnect: true, // Auto-reconnect on disconnect
maxRetries: 100, // Max reconnection attempts (default: 100)
initialBackoffDelay: 1000, // Initial backoff in ms (default: 1000)
maxBackoffDelay: 60000 // Max backoff in ms (default: 60000)
});
Two-Way Function Calls
Both server and client can define and call functions on each other:
// Server calling client
const clientFunction = new SocketFunction({
funcName: 'clientTask',
funcDef: async (data) => {
return { result: 'Task completed' };
}
});
// On client
client.addSocketFunction(clientFunction);
// On server - call the client
const socketConnection = server.socketConnections.findSync(conn => conn.alias === 'myClient');
const result = await server.clientCall('clientTask', { task: 'doSomething' }, socketConnection);
Connection Tagging
Tag connections to identify and group them:
// On client
await client.addTag({
id: 'role',
payload: 'admin'
});
// On server - find tagged connections
const adminConnections = server.socketConnections.getArray().filter(async conn => {
const tag = await conn.getTagById('role');
return tag?.payload === 'admin';
});
// Server can also tag connections
await socketConnection.addTag({
id: 'verified',
payload: true
});
Integration with Smartserve
Use smartsocket with @push.rocks/smartserve for advanced HTTP/WebSocket handling:
import { SmartServe } from '@push.rocks/smartserve';
import { Smartsocket } from '@push.rocks/smartsocket';
// Create smartsocket without a port (hooks mode)
const smartsocket = new Smartsocket({ alias: 'myServer' });
// Get WebSocket hooks and pass them to SmartServe
const wsHooks = smartsocket.getSmartserveWebSocketHooks();
const smartserve = new SmartServe({
port: 3000,
websocket: wsHooks
});
// Add socket functions as usual
smartsocket.addSocketFunction(myFunction);
// Start smartserve (smartsocket hooks mode doesn't need start())
await smartserve.start();
Handling Disconnections
The client automatically handles reconnection with exponential backoff:
const client = new SmartsocketClient({
url: 'http://localhost',
port: 3000,
alias: 'myClient',
autoReconnect: true,
maxRetries: 10,
initialBackoffDelay: 500,
maxBackoffDelay: 5000
});
// Listen for connection status changes
client.eventSubject.subscribe(status => {
console.log('Connection status:', status);
// Status can be: 'new', 'connecting', 'connected', 'disconnecting', 'timedOut'
});
await client.connect();
// Manually disconnect without auto-reconnect
await client.disconnect();
// Stop the client completely (disables auto-reconnect)
await client.stop();
Secure Connections (WSS)
For secure WebSocket connections, use HTTPS URLs:
const client = new SmartsocketClient({
url: 'https://secure.example.com', // HTTPS triggers WSS
port: 443,
alias: 'secureClient'
});
TypedRequest Integration
For strongly-typed RPC calls, define interfaces:
interface IGreetRequest {
method: 'greet';
request: { name: string };
response: { message: string };
}
// Type-safe server call
const response = await client.serverCall<IGreetRequest>('greet', { name: 'Bob' });
// response is typed as { message: string }
API Reference
Smartsocket (Server)
| Method | Description |
|---|---|
start() |
Start the WebSocket server (not needed in hooks mode) |
stop() |
Stop the server and close all connections |
addSocketFunction(fn) |
Register a function that clients can call |
clientCall(funcName, data, connection) |
Call a function on a specific client |
getSmartserveWebSocketHooks() |
Get hooks for smartserve integration |
SmartsocketClient
| Method | Description |
|---|---|
connect() |
Connect to the server |
disconnect() |
Disconnect from the server |
stop() |
Disconnect and disable auto-reconnect |
serverCall(funcName, data) |
Call a function on the server |
addSocketFunction(fn) |
Register a function the server can call |
addTag(tag) |
Add a tag to the connection |
getTagById(id) |
Get a tag by its ID |
removeTagById(id) |
Remove a tag by its ID |
SocketFunction
const fn = new SocketFunction({
funcName: 'myFunction',
funcDef: async (data, socketConnection) => {
// data: the request payload
// socketConnection: the calling connection
return { result: 'response' };
}
});
Architecture
βββββββββββββββββββ WebSocket βββββββββββββββββββ
β SmartsocketClient βββββββββββββββββββββββββββΊβ Smartsocket β
β (Browser/Node) β Native WebSocket β (Server) β
βββββββββββββββββββ βββββββββββββββββββ
β β
β SocketFunction SocketFunction β
β (serverCall) (clientCall) β
β β
βββββββββββββββββ RPC-style Calls βββββββββββββββ
License and Legal Information
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the LICENSE file.
Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
Company Information
Task Venture Capital GmbH Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
changelog.md for @push.rocks/smartsocket
2025-12-04 - 4.0.0 - BREAKING CHANGE(socketconnection)
Stricter typings, smartserve hooks, connection fixes, and tag API change
- Add unified WebSocket types and adapter interface (TWebSocket, TMessageEvent, IWebSocketLike) for browser/Node and smartserve peers
- Expose smartserve integration via getSmartserveWebSocketHooks() and adapt smartserve peers to a WebSocket-like interface (readyState getter, message/close/error dispatch)
- Improve SmartsocketClient connection logic: prevent duplicate connect attempts with isConnecting flag, ensure flags are cleared on success/failure, and tighten timeout/reconnect behavior
- Improve message parsing logging to surface JSON parse errors during authentication and normal operation
- Tighten TypeScript message and payload types (use unknown instead of any, Record<string, unknown> for tag payloads)
- SocketConnection API change: getTagById() and removeTagById() are now synchronous (no longer return Promises) β this is a breaking API change
- SocketRequest: log errors when function invocation fails and ensure pending requests are removed on errors
- Bump dependency @push.rocks/smartserve to ^1.1.2 and update README to reflect SmartServe integration changes
2025-12-03 - 3.0.0 - BREAKING CHANGE(smartsocket)
Replace setExternalServer with hooks-based SmartServe integration and refactor SocketServer to support standalone and hooks modes
- Remove setExternalServer API and add getSmartserveWebSocketHooks on Smartsocket to provide SmartServe-compatible websocket hooks.
- SocketServer.start now becomes a no-op when no port is provided (hooks mode). When a port is set, it starts a standalone HTTP + ws server as before.
- Introduce an adapter (createWsLikeFromPeer) to adapt SmartServe peers to a WebSocket-like interface and route onMessage/onClose/onError via the adapter.
- Dispatch smartserve messages through the adapter: text/binary handling for onMessage, and dispatchClose/dispatchError for close/error events.
- Update tests: add smartserve integration test (test.smartserve.ts), adjust tagging test cleanup to stop client and delay before exit, remove outdated expressserver test.
2025-03-10 - 2.1.0 - feat(SmartsocketClient)
Improve client reconnection logic with exponential backoff and jitter; update socket.io and @types/node dependencies
- Bump engine.io from 6.5.4 to 6.6.4, socket.io and socket.io-client from 4.7.5 to 4.8.1
- Bump @types/node from ^20.12.7 to ^22.13.10
- Add new optional reconnection parameters (maxRetries, initialBackoffDelay, maxBackoffDelay) to SmartsocketClient options
- Implement exponential backoff with jitter for auto-reconnect and reset reconnection state on successful connection
2024-05-29 - 2.0.27 - docs
update description
2024-04-26 to 2024-03-30 - 2.0.26 β¦ 2.0.24 - core & configuration
A series of internal fixes and configuration tweaks.
- fix(core): update
- update tsconfig
- update npmextra.json: githost
2023-09-10 to 2023-07-21 - 2.0.23 β¦ 2.0.20 - core
Multiple minor core fixes were applied in rapid succession.
- fix(core): update
2023-07-21 to 2023-03-20 - 2.0.19 β¦ 2.0.15 - core
Routine internal updates addressing core functionality.
- fix(core): update
2023-02-07 to 2022-03-24 - 2.0.14 β¦ 2.0.0 - core
Further minor core updates were rolled out over several versions.
- fix(core): update
2022-03-14 - 1.2.22 - esm
A breaking change was introduced to switch the module system.
- BREAKING CHANGE(switch to esm): update
2022-01-20 to 2021-01-23 - 1.2.21 β¦ 1.2.0 - core
A range of minor core fixes.
- fix(core): update
2020-12-26 - 1.1.71 - SmartsocketClient
New functionality in the socket client was added.
- feat(SmartsocketClient): socket client can now be stopped with .stop() in addition to .reconnect()
2020-12-26 to 2020-09-24 - 1.1.70 β¦ 1.1.58 - core & test
A group of updates addressing both core mechanics and tests.
- fix(core): update
- fix(test): use @pushrocks/isohash instead of @pushrocks/smarthash
2019-11-08 to 2019-04-23 - 1.1.57 β¦ 1.1.27 - core
Numerous versions in this period included only internal core fixes.
- fix(core): update
2019-01-31 to 2019-01-30 - 1.1.26 β¦ 1.1.19 - build, docs & configuration
Updates went beyond the core, affecting build tooling and package metadata.
- fix(build): now building with tsbuild
- fix(readme): update
- fix(npmextra): adjust access level
- fix(scope): switch to @pushrocks
- fix(package.json): private setting
- fix(snyk): add .snyk file
- fix(structure): update to latest standards
2018-03-19 to 2018-03-15 - 1.1.18 β¦ 1.1.12 - core & docs
Several improvements touching both functionality and documentation.
- now working as expected
- start transitioning to better SocketFunction handling
- add @types/node
- format and update README
- update to latest standards
2017-10-09 to 2017-07-07 - 1.1.11 β¦ 1.1.07 - core & docs
Updates in this range improved both the internal mechanics and the developerβfacing materials.
- allow setting of specific server
- fix not ending error correctly
- update to newest version
- update docs and tests
- remove taskbuffer
- update to latest standards
2016-09-25 to 2016-09-03 - 1.1.6 β¦ 1.1.3 - docs & core
Minor improvements in documentation and code quality.
- improve README
- added docs
- fix scoping of socket roles and perform small syntax fixes
2016-09-02 to 2016-08-16 - 1.1.2 β¦ 1.1.1 - dependencies & security
Several housekeeping tasks to update dependencies and improve security.
- updated dependencies and exported socketConnection
- now authenticating sockets by checking the password hash
2016-08-15 - 1.1.0 - docs
A documentation update was published.
- update README
2016-08-15 - 1.0.7 - networking
A key update made the socket client work bi-directionally, enabling mesh setups.
- now working in both directions so mesh setups work
2016-08-14 to 2016-08-07 - 1.0.6 β¦ 1.0.0 - internal changes
From the initial release onward, several internal improvements were introduced:
- updated tests and structure
- reworked reconnection logic and added a request/response abstraction for transparent function calls
- initial release features with updated documentation and structure