- Updated test files to use new testing library and reduced test cycles for efficiency. - Removed dependency on smartexpress and integrated direct WebSocket handling. - Enhanced Smartsocket and SmartsocketClient classes to support new message types and authentication flow. - Implemented a new message interface for structured communication between client and server. - Added external server support for smartserve with appropriate WebSocket hooks. - Improved connection management and error handling in SocketConnection and SocketRequest classes. - Cleaned up code and removed deprecated socket.io references in favor of native WebSocket.
@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';
const smartserve = new Smartserve({ port: 3000 });
const smartsocket = new Smartsocket({ alias: 'myServer' });
// Set smartserve as external server
await smartsocket.setExternalServer('smartserve', smartserve);
// Get WebSocket hooks for smartserve
const wsHooks = smartsocket.socketServer.getSmartserveWebSocketHooks();
// Configure smartserve with the hooks
// (see smartserve documentation for integration details)
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 |
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 |
setExternalServer(type, server) |
Use an external server (smartserve) |
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.