netcore-networking
v1.1.3
Published
Production-ready networking system for multiplayer games with NetCore architecture
Maintainers
Readme
NetCore Networking
A production-ready networking system for multiplayer games with NetCore architecture. This package provides a complete networking solution with real-time communication, security features, and performance monitoring.
Features
Core Networking
- 128Hz Server Tick Rate - High-frequency game state updates
- Client-Side Interpolation - Smooth gameplay despite network jitter
- Server-Side Prediction - Handles latency and input validation
- Real-Time Communication - WebSocket-based bidirectional messaging
- Automatic Reconnection - Robust connection handling
Transport Options
- WebSocket Transport - Reliable TCP-based communication (default)
- UDP Transport - High-performance, low-latency communication
- Hybrid Transport - Automatic switching between WebSocket and UDP
- Auto-Detection - Smart transport selection based on network conditions
- Transport Switching - Runtime switching between transport layers
- Transport Manager - Unified management of multiple transport layers
Security Features
- Rate Limiting - Prevents spam and abuse
- Input Validation - Validates all client inputs
- IP Whitelisting/Blacklisting - Access control
- Connection Monitoring - Tracks suspicious activity
- Automatic Banning - Temporary bans for violations
- Session Management - Secure session tokens and validation
- Anti-Cheat Plugin System - Easy-to-use plugin architecture for custom anti-cheat
- Enhanced Security - Encryption, DDoS protection, and client integrity verification
- Transport-Agnostic Security - Security features work across all transport layers
Session Management
- Game Sessions - Create and manage multiple game sessions
- Player Management - Join, leave, and track players in sessions
- Session Settings - Configurable game rules and parameters
- Auto-Cleanup - Automatic cleanup of inactive sessions
- Session Statistics - Monitor session performance and activity
Multi-Instance Support
- Load Balancing - Distribute players across multiple server instances
- Auto-Scaling - Automatically create/remove instances based on demand
- Instance Management - Monitor and manage multiple server instances
- Port Management - Automatic port allocation for new instances
- Performance Monitoring - Track performance across all instances
Performance Monitoring
- Real-Time Metrics - Ping, packet loss, jitter tracking
- Connection Quality Assessment - Automatic quality scoring
- Performance Alerts - Automatic issue detection
- Bandwidth Monitoring - Network usage tracking
- System Statistics - CPU, memory, and network stats
Developer Tools
- TypeScript Support - Full type safety
- Configuration Management - Flexible server configuration
- Network Utilities - Common networking functions
- Performance Analysis - Detailed metrics and reporting
Installation
📦 Note: Version 1.1.0 had a dependency issue that prevented downloads. Please use version 1.1.1 or later.
Using Bun (Recommended)
bun add netcore-networkingUsing npm
npm install netcore-networkingUsing yarn
yarn add netcore-networkingQuick Start
Server Setup
import { createServer, DEFAULT_CONFIG } from "netcore-networking";
// Create server with default configuration
const server = createServer(8080, DEFAULT_CONFIG);
// Start the server
await server.start(); // Note: start() is now async
// Handle graceful shutdown
process.on("SIGINT", () => {
server.stop();
process.exit(0);
});Client Setup
import { NetCoreClient } from "netcore-networking";
// Create client
const client = new NetCoreClient("ws://localhost:8080");
// Set handshake data (REQUIRED: checksum and version)
client.setHandshakeData("your-client-checksum", "1.0.0");
// Connect to server
await client.connect();
// Send player input
client.sendInput({
movement: { x: 1, y: 0 },
actions: { shoot: true, jump: false },
});
// Get network statistics
const stats = client.getNetworkStats();
console.log(`Ping: ${stats.ping}ms, Packet Loss: ${stats.packetLoss}%`);⚠️ Important: You must call
setHandshakeData(checksum, version)before connecting. The server will reject clients that do not provide a valid handshake.
Transport Configuration
NetCore supports multiple transport layers with a unified Transport Manager system:
WebSocket Transport (Default)
// Default WebSocket transport
const server = createServer(8080, {
transport: {
primaryTransport: "websocket",
websocket: {
enabled: true,
port: 8080,
host: "0.0.0.0",
maxPayload: 1024 * 1024, // 1MB
perMessageDeflate: false,
},
},
});UDP Transport (High Performance)
// High-performance UDP transport for hardcore FPS
const server = createServer(8080, {
transport: {
primaryTransport: "udp",
udp: {
enabled: true,
port: 8081,
host: "0.0.0.0",
enableReliableUDP: true,
enablePacketOrdering: true,
enableFragmentation: true,
maxPacketSize: 1400, // MTU-safe
fragmentSize: 1024,
retransmitTimeout: 100, // ms
maxRetransmits: 3,
sendBufferSize: 1024 * 1024, // 1MB
receiveBufferSize: 1024 * 1024, // 1MB
enableQoS: true,
priorityLevels: 4,
enablePerformanceMetrics: true,
},
},
});Hybrid Transport (Best of Both Worlds)
// Hybrid transport - automatic switching
const server = createServer(8080, {
transport: {
primaryTransport: "hybrid",
hybrid: {
enabled: true,
useWebSocketForReliable: true, // Reliable data via WebSocket
useUDPForFast: true, // Fast data via UDP
switchThreshold: 50, // 50ms latency difference
},
},
});Auto-Detection Transport
// Smart transport selection
const server = createServer(8080, {
transport: {
primaryTransport: "auto",
auto: {
enabled: true,
latencyThreshold: 100, // Use UDP if latency < 100ms
packetLossThreshold: 5, // Switch to WebSocket if packet loss > 5%
switchCooldown: 5000, // Minimum 5s between switches
},
},
});Transport Manager Integration
The new Transport Manager provides unified management of multiple transport layers:
import { TransportManager, UDPTransport } from "netcore-networking";
// Create a transport manager
const transportManager = new TransportManager({
primaryTransport: "hybrid",
websocket: {
enabled: true,
port: 8080,
host: "0.0.0.0",
maxPayload: 1024 * 1024,
perMessageDeflate: true,
},
udp: {
enabled: true,
port: 8081,
host: "0.0.0.0",
enableReliableUDP: true,
enablePacketOrdering: true,
enableFragmentation: false,
maxPacketSize: 1024,
fragmentSize: 1024,
retransmitTimeout: 1000,
maxRetransmits: 3,
sendBufferSize: 1024 * 1024,
receiveBufferSize: 1024 * 1024,
enableQoS: false,
priorityLevels: 0,
enablePacketLogging: false,
enablePerformanceMetrics: true,
},
hybrid: {
enabled: true,
useWebSocketForReliable: true,
useUDPForFast: false,
switchThreshold: 100,
},
auto: {
enabled: false,
latencyThreshold: 50,
packetLossThreshold: 0.1,
switchCooldown: 1000,
},
});
// Start the transport manager
await transportManager.start();
// Send data via the transport manager
transportManager.send("Hello World", "client-id", {
reliable: true,
ordered: true,
priority: 1,
});
// Get transport statistics
const stats = transportManager.getStats();
console.log(`Active transport: ${stats.activeTransport}`);
console.log(`UDP latency: ${stats.udp.latency}ms`);
console.log(`WebSocket latency: ${stats.websocket.latency}ms`);Performance Comparison
| Transport | Latency | Throughput | Reliability | Use Case | Security Integration | | --------- | -------- | ---------- | ------------ | -------------------------------------- | --------------------- | | WebSocket | ~50ms | ~1MB/s | High | General purpose, reliable data | Full security support | | UDP | ~5ms | ~10MB/s | Configurable | High-performance games, real-time data | Full security support | | Hybrid | Adaptive | Adaptive | High | Best of both worlds | Full security support | | Auto | Adaptive | Adaptive | High | Smart selection based on conditions | Full security support |
Security Integration Across Transports
All security features work seamlessly across transport layers:
// Security features work with any transport
const secureServer = createServer(8080, {
enableSecurity: true,
transport: {
primaryTransport: "udp", // Even UDP gets full security
udp: {
enabled: true,
port: 8081,
// ... UDP config
},
},
encryption: {
enabled: true,
algorithm: "aes-256-gcm",
keyRotationInterval: 300000,
},
ddosProtection: {
enabled: true,
maxConnectionsPerIP: 5,
maxRequestsPerSecond: 100,
},
clientIntegrity: {
enabled: true,
enableChecksumValidation: true,
enableBehaviorAnalysis: true,
},
});Anti-Cheat Plugin System
The NetCore networking system includes a powerful anti-cheat plugin architecture that makes it easy for developers to implement custom anti-cheat solutions.
Creating Custom Anti-Cheat Plugins
import {
BaseAntiCheatPlugin,
ValidationResult,
PlayerState,
} from "netcore-networking";
class CustomSpeedHackDetector extends BaseAntiCheatPlugin {
constructor() {
super("CustomSpeedHackDetector", "1.0.0");
}
initialize(config?: any): void {
console.log("Custom speed hack detector initialized");
}
validatePlayerAction(playerId: number, action: any): ValidationResult {
// Your custom logic here
return { valid: true, severity: "low", action: "ignore" };
}
validatePlayerState(playerId: number, state: PlayerState): ValidationResult {
// Your custom logic here
return { valid: true, severity: "low", action: "ignore" };
}
}Using Anti-Cheat Plugins
import {
NetCoreServer,
AntiCheatManager,
SpeedHackDetector,
TeleportDetector,
} from "netcore-networking";
// Create server and anti-cheat manager
const server = new NetCoreServer(8080);
const antiCheatManager = new AntiCheatManager({
enabled: true,
autoAction: true,
logViolations: true,
maxViolationsPerPlayer: 3,
});
// Register built-in plugins
antiCheatManager.registerPlugin(new SpeedHackDetector());
antiCheatManager.registerPlugin(new TeleportDetector());
// Register your custom plugin
antiCheatManager.registerPlugin(new CustomSpeedHackDetector());
// Configure plugins
antiCheatManager.getPlugin("SpeedHackDetector")?.initialize({
maxSpeed: 15,
});
// Start the server
await server.start();Built-in Anti-Cheat Plugins
- SpeedHackDetector - Detects players moving too fast
- TeleportDetector - Detects impossible position changes
- BaseAntiCheatPlugin - Base class for creating custom plugins
Session Management
Create and manage multiple game sessions with different settings and player limits.
import { SessionManager } from "netcore-networking";
const sessionManager = new SessionManager({
maxSessions: 10,
sessionTimeout: 300000, // 5 minutes
defaultSettings: {
tickRate: 128,
maxPing: 200,
allowSpectators: true,
autoBalance: true,
roundTime: 120000, // 2 minutes
maxRounds: 30,
},
});
// Create a new session
const session = sessionManager.createSession(
"My Game",
"deathmatch",
"map1",
10
);
// Join a player to the session
sessionManager.joinSession(session.id, clientId, "Player1", 1);
// Get session statistics
const stats = sessionManager.getSessionStats();
console.log(`Active sessions: ${stats.activeSessions}`);Multi-Instance Server
Run multiple server instances with automatic load balancing and scaling.
import { createMultiInstanceServer } from "netcore-networking";
const multiServer = createMultiInstanceServer(8080, {
maxInstances: 5,
autoScale: true,
loadBalancing: true,
sessionManager: true,
});
// Start the multi-instance server
await multiServer.start();
// Get the session manager
const sessionManager = multiServer.getSessionManager();
// Create a session
const session = sessionManager.createSession("Game1", "deathmatch", "map1", 8);
// Auto-creates an instance for the session
const instance = multiServer.createInstance(session.id, session);
// Get instance statistics
const stats = multiServer.getInstanceStats();
console.log(`Active instances: ${stats.activeInstances}`);Advanced Configuration
import { createNetworkConfig, validateNetworkConfig } from "netcore-networking";
// Create custom configuration
const config = createNetworkConfig({
tickRate: 128,
maxClients: 20,
enableSecurity: true,
transport: {
primaryTransport: "hybrid",
websocket: {
enabled: true,
port: 8080,
host: "0.0.0.0",
maxPayload: 1024 * 1024,
perMessageDeflate: true,
},
udp: {
enabled: true,
port: 8081,
host: "0.0.0.0",
enableReliableUDP: true,
enablePacketOrdering: true,
enableFragmentation: false,
maxPacketSize: 1024,
fragmentSize: 1024,
retransmitTimeout: 1000,
maxRetransmits: 3,
sendBufferSize: 1024 * 1024,
receiveBufferSize: 1024 * 1024,
enableQoS: false,
priorityLevels: 0,
enablePacketLogging: false,
enablePerformanceMetrics: true,
},
hybrid: {
enabled: true,
useWebSocketForReliable: true,
useUDPForFast: false,
switchThreshold: 100,
},
auto: {
enabled: false,
latencyThreshold: 50,
packetLossThreshold: 0.1,
switchCooldown: 1000,
},
},
rateLimit: {
maxMessagesPerSecond: 100,
maxInputsPerSecond: 60,
burstLimit: 10,
},
security: {
requireAuthentication: false,
maxFailedAttempts: 5,
banDuration: 300000,
},
});
// Validate configuration
const errors = validateNetworkConfig(config);
if (errors.length > 0) {
console.error("Configuration errors:", errors);
}
// Create server with custom config
const server = createServer(8080, config);API Reference
Server
NetCoreServer
Main server class for handling game networking with transport-agnostic architecture.
class NetCoreServer {
constructor(port: number, config?: Partial<NetworkConfig>);
start(): Promise<void>; // Now async
stop(): void;
getNetworkStats(): NetworkStats[];
getConnectedClients(): ClientConnection[];
getServerInfo(): ServerInfo;
getDetailedNetworkStats(): DetailedNetworkStats;
}TransportManager
Manages multiple transport layers with automatic switching and fallback.
class TransportManager {
constructor(config: Partial<TransportConfig>);
start(): Promise<void>;
stop(): void;
send(data: Buffer | string, target: string, options?: SendOptions): number;
switchTransport(transport: TransportType): void;
getStats(): TransportStats;
getConfig(): TransportConfig;
}UDPTransport
High-performance UDP transport with configurable reliability features.
class UDPTransport {
constructor(config: Partial<UDPConfig>, isServer?: boolean);
start(): Promise<void>;
stop(): void;
send(
data: Buffer | string,
address: string,
port: number,
options?: SendOptions
): number;
getStats(): UDPStats;
getConfig(): UDPConfig;
}Client
NetCoreClient
Client class for connecting to NetCore servers.
class NetCoreClient {
constructor(serverUrl: string);
setHandshakeData(checksum: string, version: string): void;
connect(): Promise<number>;
disconnect(): void;
sendInput(input: Partial<PlayerInput>): void;
getNetworkStats(): NetworkStats;
isClientConnected(): boolean;
getClientId(): number | null;
getPing(): number;
}Security
EnhancedSecurityManager
Comprehensive security manager with encryption, DDoS protection, and client integrity.
class EnhancedSecurityManager {
constructor(config: Partial<EnhancedSecurityConfig>);
start(): void;
stop(): void;
canConnect(clientId: number, ipAddress: string): SecurityCheck;
canRequest(clientId: number, ipAddress: string): SecurityCheck;
registerClient(clientId: number, checksum: string, version: string): void;
createEncryptionSession(clientId: number): string | null;
encrypt(sessionId: string, data: string): EncryptedMessage | null;
decrypt(message: EncryptedMessage): string | null;
getMetrics(): SecurityMetrics;
}AntiCheatManager
Manages anti-cheat plugins and validation.
class AntiCheatManager {
constructor(config?: Partial<AntiCheatManagerConfig>);
registerPlugin(plugin: AntiCheatPlugin): boolean;
unregisterPlugin(pluginName: string): boolean;
validatePlayerAction(playerId: number, action: any): ValidationResult;
validatePlayerState(playerId: number, state: PlayerState): ValidationResult;
getPlugin(pluginName: string): AntiCheatPlugin | undefined;
getPlugins(): AntiCheatPlugin[];
getCombinedStats(): AntiCheatStats;
}Performance Monitoring
const monitor = new PerformanceMonitor();
// Record metrics
monitor.recordTick(serverTick, connectedClients);
monitor.recordClientMetrics(clientId, ping, packetLoss, jitter);
// Get alerts
const alerts = monitor.getPerformanceAlerts();
alerts.forEach((alert) => console.warn(alert));
// Get metrics history
const history = monitor.getMetricsHistory(300); // Last 5 minutesNetwork Statistics
// Get server statistics
const serverStats = server.getNetworkStats();
serverStats.forEach((stat) => {
console.log(
`Client ${stat.clientId}: ${stat.ping}ms ping, ${stat.packetLoss}% loss`
);
});
// Get detailed network statistics with transport info
const detailedStats = server.getDetailedNetworkStats();
detailedStats.clients.forEach((client) => {
console.log(
`Client ${client.id} (${client.transport}): ${client.ping}ms ping, ${client.packetLoss} loss`
);
});
// Get client statistics
const clientStats = client.getNetworkStats();
const summary = NetworkUtils.getNetworkSummary(clientStats);
console.log(`Connection Quality: ${summary.quality} (${summary.score}/100)`);Troubleshooting
Common Issues
High Ping
- Check network connection
- Reduce server load
- Optimize game logic
- Consider using UDP transport for better performance
Packet Loss
- Check network stability
- Reduce packet size
- Enable compression
- Use reliable UDP or switch to WebSocket
Connection Drops
- Check firewall settings
- Verify server availability
- Increase timeout values
- Check transport configuration
Handshake Failures
- Ensure
setHandshakeData()is called beforeconnect() - Verify checksum and version are valid
- Check server security settings
- Ensure
Transport Issues
- Verify transport configuration
- Check port availability
- Ensure transport manager is properly initialized
- Review transport statistics for issues
Debug Mode
// Enable debug logging
const debugConfig = createNetworkConfig({
enableSecurity: true,
enableCompression: false,
maxPacketSize: 2048,
transport: {
primaryTransport: "websocket", // Start with reliable transport
websocket: {
enabled: true,
port: 8080,
host: "0.0.0.0",
maxPayload: 1024 * 1024,
perMessageDeflate: false, // Disable compression for debugging
},
},
});
// Monitor performance
const monitor = new PerformanceMonitor();
setInterval(() => {
const metrics = monitor.getCurrentMetrics();
if (metrics) {
console.log("Performance:", metrics);
}
}, 1000);
// Monitor transport statistics
setInterval(() => {
const serverInfo = server.getServerInfo();
if (serverInfo.transport) {
console.log("Transport Stats:", serverInfo.transport.stats);
}
}, 5000);License
MIT License - see LICENSE file for details.
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
Support
For support and questions:
- Create an issue on GitHub
- Check the documentation
- Review the examples
Version History
1.0.0 - Initial Release
- Core Features: Security and performance monitoring
- Language Support: TypeScript support
- Architecture: Production-ready architecture
- Communication: WebSocket-based communication
- Security: Basic anti-cheat system
1.0.1 - Enhanced Security and Stability
- Encryption: Improved encryption system
- DDoS Protection: Better DDoS protection
- Client Integrity: Enhanced client integrity verification
- Performance: Bug fixes and performance improvements
1.0.2 - Transport System Improvements
- WebSocket: Enhanced WebSocket transport
- Error Handling: Improved error handling
- Connection Management: Better connection management
- Security: Additional security features
1.1.0 - Major Transport System Update
- UDP Transport: Added UDP transport with configurable reliability
- Transport Manager: Unified transport management
- Hybrid Transport: WebSocket + UDP combination
- Auto-Detection: Smart transport switching
- Security Integration: Transport-agnostic security features
- Performance Monitoring: Enhanced monitoring capabilities
- Documentation: Improved documentation and examples
1.1.1 - Dependency Fix and Maintenance
- Fixed: Removed unused uWebSockets.js dependency that was causing 404 download errors
- Maintenance: Cleaned up package dependencies
- No breaking changes: All functionality remains identical
- Improved reliability: Package now downloads successfully from npm
1.1.2 - Dependency Cleanup and Maintenance
- Fixed: Removed unused uWebSockets.js dependency that was causing 404 download errors
- Maintenance: Removed unused
enetdependency as precautionary cleanup - Dependency Optimization: Streamlined package dependencies for better reliability
- No breaking changes: All functionality remains identical
- Improved reliability: Package now downloads successfully from npm
1.1.3 - Critical Bug Fix: Double Server Startup Issue
- Fixed: Resolved critical issue where server was starting twice, causing port conflicts
- Removed: Eliminated unused
MainServerclass that was causing automatic server startup - Cleanup: Removed
main-server.tsfile that was not being used - Package.json: Fixed conflicting module field in package.json
- No breaking changes: All existing APIs remain unchanged
- Improved reliability: Server now starts correctly without port conflicts
