Refactor smartsocket implementation for improved WebSocket handling and message protocol

- 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.
This commit is contained in:
2025-12-03 02:20:38 +00:00
parent ee59471e14
commit 1d62c9c695
14 changed files with 3901 additions and 3007 deletions

294
readme.md
View File

@@ -1,149 +1,291 @@
# @push.rocks/smartsocket
easy and secure websocket communication
Easy and secure WebSocket communication with native WebSocket support 🔌
## Features
- 🚀 **Native WebSocket** - Uses native WebSocket API (browser) and `ws` library (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/](https://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/](https://code.foss.global/) account to submit Pull Requests directly.
## Install
To install @push.rocks/smartsocket, you can use npm or yarn as follows:
```shell
npm install @push.rocks/smartsocket --save
```
or
or with pnpm:
```shell
yarn add @push.rocks/smartsocket
pnpm add @push.rocks/smartsocket
```
## Usage
@push.rocks/smartsocket offers a robust solution for easy and secure WebSocket communication, utilizing Typescript for clean and maintainable code. Below are comprehensive examples covering various scenarios and features provided by the module.
### Getting Started
First, ensure you've installed the module as shown in the "Install" section. Once installed, you can start using @push.rocks/smartsocket in your project.
### Setting Up a WebSocket Server
To create a WebSocket server that clients can connect to:
### Quick Start - Server
```typescript
import { Smartsocket } from '@push.rocks/smartsocket';
import { Smartsocket, SocketFunction } from '@push.rocks/smartsocket';
// Create a new instance of Smartsocket for the server.
const server = new Smartsocket({ alias: 'myServer' });
// Create server
const server = new Smartsocket({
alias: 'myServer',
port: 3000
});
// Define a SocketFunction that clients can call
server.addSocketFunction({
// Define a function that clients can call
const greetFunction = new SocketFunction({
funcName: 'greet',
funcDef: async (data) => {
console.log(`Server received: ${data.message}`);
return { reply: `Hello, ${data.name}!` };
funcDef: async (data, socketConnection) => {
console.log(`Received greeting from ${data.name}`);
return { message: `Hello, ${data.name}!` };
}
});
// Start the Smartsocket server
server.start().then(() => {
console.log('WebSocket server is running...');
});
server.addSocketFunction(greetFunction);
// Start the server
await server.start();
console.log('WebSocket server running on port 3000');
```
### Creating a WebSocket Client
Create a client that connects to the WebSocket server and interacts with it:
### Quick Start - Client
```typescript
import { SmartsocketClient } from '@push.rocks/smartsocket';
// Create a SmartsocketClient instance and connect to the server
// Create client
const client = new SmartsocketClient({
url: 'ws://localhost',
url: 'http://localhost',
port: 3000,
alias: 'myClient'
alias: 'myClient',
autoReconnect: true
});
client.connect().then(() => {
console.log('Connected to WebSocket server');
});
// Connect to server
await client.connect();
// Define a function to call the server's 'greet' function
async function greetServer(name) {
const response = await client.serverCall('greet', { name: name, message: 'Hello!' });
console.log(`Server replied: ${response.reply}`);
}
// Use the function
greetServer('Alice');
// Call server function
const response = await client.serverCall('greet', { name: 'Alice' });
console.log(response.message); // "Hello, Alice!"
```
### Handling Disconnections and Reconnections
### Connection Options
@push.rocks/smartsocket provides mechanisms to handle client disconnections and attempt reconnections:
The `SmartsocketClient` supports several configuration options:
```typescript
client.on('disconnect', () => {
console.log('Disconnected from server. Attempting to reconnect...');
client.connect();
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)
});
```
### Sending Binary Data
### Two-Way Function Calls
The library supports the transmission of binary data efficiently:
Both server and client can define and call functions on each other:
```typescript
import fs from 'fs';
// Server calling client
const clientFunction = new SocketFunction({
funcName: 'clientTask',
funcDef: async (data) => {
return { result: 'Task completed' };
}
});
// Function to send a binary file to the server
async function sendBinaryData(filePath) {
const fileBuffer = fs.readFileSync(filePath);
await client.serverCall('sendFile', { file: fileBuffer });
}
// On client
client.addSocketFunction(clientFunction);
sendBinaryData('./path/to/your/file.png');
// On server - call the client
const socketConnection = server.socketConnections.findSync(conn => conn.alias === 'myClient');
const result = await server.clientCall('clientTask', { task: 'doSomething' }, socketConnection);
```
### Securing Your WebSocket Communication
### Connection Tagging
@push.rocks/smartsocket leverages secure WebSocket (WSS) connections to ensure that data transferred between the client and server is encrypted. When setting up your Smartsocket server or client, use `wss://` in your URL to enable secure communication.
Tag connections to identify and group them:
### Advanced Usage
```typescript
// On client
await client.addTag({
id: 'role',
payload: 'admin'
});
#### Mesh Networking
// On server - find tagged connections
const adminConnections = server.socketConnections.getArray().filter(async conn => {
const tag = await conn.getTagById('role');
return tag?.payload === 'admin';
});
@push.rocks/smartsocket allows for the creation of complex mesh network configurations, enabling servers to communicate with other servers, forming a robust network with multiple nodes.
// Server can also tag connections
await socketConnection.addTag({
id: 'verified',
payload: true
});
```
#### Scaling with @push.rocks/smartsocket
### Integration with Smartserve
To scale your WebSocket services, you can utilize load balancers and ensure your @push.rocks/smartsocket instances are stateless to allow for horizontal scaling.
Use smartsocket with `@push.rocks/smartserve` for advanced HTTP/WebSocket handling:
### Conclusion
```typescript
import { Smartserve } from '@push.rocks/smartserve';
import { Smartsocket } from '@push.rocks/smartsocket';
This guide has covered how to set up basic WebSocket communication with @push.rocks/smartsocket, handle disconnections/reconnections, secure your communication, send binary data, and briefly touched on advanced concepts like mesh networking and scaling.
const smartserve = new Smartserve({ port: 3000 });
const smartsocket = new Smartsocket({ alias: 'myServer' });
For more detailed documentation, visit [the official @push.rocks/smartsocket GitLab repository](https://gitlab.com/pushrocks/smartsocket).
// Set smartserve as external server
await smartsocket.setExternalServer('smartserve', smartserve);
Remember, WebSocket communication with @push.rocks/smartsocket is not only about sending and receiving messages. It's about creating a fast, reliable, and secure communication channel for your real-time applications.
// Get WebSocket hooks for smartserve
const wsHooks = smartsocket.socketServer.getSmartserveWebSocketHooks();
Happy coding!
// Configure smartserve with the hooks
// (see smartserve documentation for integration details)
```
---
### Handling Disconnections
Please note, the documentation above is a starting point. Depending on the complexity and requirements of your application, you may need to explore more features and configurations provided by @push.rocks/smartsocket. Always refer to the official documentation for the most current information and best practices.
The client automatically handles reconnection with exponential backoff:
```typescript
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:
```typescript
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:
```typescript
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
```typescript
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 that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./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 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, and any usage must be approved in writing by Task Venture Capital GmbH.
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
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
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.