This implementation provides the HyperTCP protocol - a lightweight, real-time TCP-based protocol for hardware-to-server and server-to-web communication. It's designed as a pure alternative to WebSocket and other protocols, running directly on the TCP layer.
- Pure TCP Implementation: No WebSocket, HTTP, or other intermediate protocols
- Lightweight: Minimal overhead for efficient communication
- Real-time: Low-latency communication for time-sensitive applications
- Cross-Platform: Works with hardware devices, servers, and web applications
- JSON Message Support: Flexible JSON payloads for complex data structures
- Authentication: Token-based authentication for security
- Keepalive: Automatic ping/pong mechanism for connection health
- Broadcast Messaging: Send messages to all connected clients
- Server Redirection: Supports server redirection for load balancing
- Extensible: Easy to add new command types
struct HyperTCPHeader {
uint8_t type; // Command type
uint16_t msg_id; // Message ID
uint16_t length; // Payload length
};
HYPER_TCP_CMD_RESPONSE(0): Response to commandsHYPER_TCP_CMD_PING(6): Keepalive messageHYPER_TCP_CMD_LOGIN(29): AuthenticationHYPER_TCP_CMD_JSON_MESSAGE(30): JSON messagesHYPER_TCP_CMD_REDIRECT(41): Server redirectionHYPER_TCP_CMD_BROADCAST(50): Broadcast message to all clients
HYPER_TCP_STATUS_SUCCESS(200): Operation successfulHYPER_TCP_STATUS_INVALID_TOKEN(9): Invalid authentication tokenHYPER_TCP_STATUS_NOT_AUTHENTICATED(5): Client not authenticatedHYPER_TCP_STATUS_TIMEOUT(16): Operation timed out
{
"targetId": "receiver_id",
"payload": {
// Your data here
}
}{
"from": "sender_id",
"payload": {
// Your data here
}
}- Include the header file:
#include "HyperTCPProtocol.h"- Set up the transport:
WiFiClient wifiClient;
HyperTCPTransport<WiFiClient> myTransport(wifiClient);- Create the protocol instance:
HyperTCPProtocol<HyperTCPTransport<WiFiClient>> myProtocol(myTransport);- Connect with authentication:
myProtocol.connect("your_auth_token", "your-server.com", 8080);- Send messages:
// Method 1: Using JsonObject
DynamicJsonDocument doc(256);
doc["temperature"] = 25.6;
myProtocol.sendMessage("server", doc.as<JsonObject>());
// Method 2: Using JSON string
const char* payload = "{\"temperature\": 25.6}";
myProtocol.sendMessage("server", payload);
// Method 3: Broadcast to all clients
DynamicJsonDocument broadcastDoc(256);
broadcastDoc["notification"] = "System update available";
myProtocol.broadcastMessage(broadcastDoc.as<JsonObject>());
// Method 4: Send directly to server
DynamicJsonDocument serverDoc(256);
serverDoc["status"] = "online";
myProtocol.sendToServer(serverDoc.as<JsonObject>());- Handle incoming messages:
class MyProtocolWithHandlers : public HyperTCPProtocol<HyperTCPTransport<WiFiClient>> {
public:
MyProtocolWithHandlers(HyperTCPTransport<WiFiClient>& transport)
: HyperTCPProtocol<HyperTCPTransport<WiFiClient>>(transport) {}
void onMessageReceived(const char* from, JsonObject& payload) override {
// Handle incoming messages
Serial.print("Message from: ");
Serial.println(from);
// Process payload...
}
void onBroadcastMessage(const char* from, JsonObject& payload) override {
// Handle broadcast messages
Serial.print("Broadcast from: ");
Serial.println(from);
// Process payload...
}
};- Run the protocol loop:
void loop() {
myProtocol.run(); // Call this regularly
}The Python server implementation (HyperTCPTestServer.py) provides:
- Pure TCP Server: No WebSocket or HTTP dependencies
- Multi-client Support: Handles multiple concurrent connections
- Message Routing: Routes messages between clients
- Authentication: Token-based client authentication
- Broadcast Support: Send messages to all connected clients
- Keepalive: Monitors connection health with ping/pong
python HyperTCPTestServer.py- Hardware devices can send data to the server
- Server can send commands to specific devices
- Server can push commands and updates to devices
- Real-time control of hardware
- Devices can communicate directly through the server
- Server acts as message broker
- Messages can be sent to all connected clients
- Useful for notifications and system-wide commands
{
"targetId": "server",
"payload": {
"temperature": 25.6,
"humidity": 65.3,
"timestamp": 1234567890
}
}{
"targetId": "device_192.168.1.100_8080",
"payload": {
"command": "control",
"device": "relay_1",
"action": "toggle",
"value": 1
}
}// Outgoing ping
{
"targetId": "server",
"payload": {
"command": "ping",
"timestamp": 1234567890
}
}
// Incoming pong
{
"from": "server",
"payload": {
"command": "pong",
"timestamp": 1234567890
}
}{
"targetId": "broadcast",
"payload": {
"command": "notification",
"message": "System maintenance in 5 minutes",
"urgency": "medium"
}
}- Upload HyperTCPExample.ino to your ESP32
- Update WiFi credentials and server IP
- Run the HyperTCP server
- Monitor serial output to see messages being exchanged
- Run:
python HyperTCPTestServer.py - Connect devices or use a TCP client to test
- Monitor server console for message logs
- Efficiency: Pure TCP with minimal overhead
- Simplicity: No complex protocol layers
- Real-time: Low-latency communication
- Flexibility: JSON payloads for complex data
- Reliability: Built-in error handling and connection management
- Scalability: Can handle multiple connections efficiently
- Security: Token-based authentication
- Compatibility: Works with existing network infrastructure
- Memory Usage: JSON parsing requires memory - optimize buffer sizes for constrained devices
- Bandwidth: JSON messages are larger than binary equivalents but still efficient
- Processing Time: JSON parsing is slower than binary but acceptable for most applications
- Connection Management: TCP connections are more resource-intensive than UDP but provide reliability
For production use, consider:
- Adding encryption (TLS/SSL for the transport)
- Implementing proper authentication with secure tokens
- Adding message integrity checks
- Including timestamps to prevent replay attacks
- Implementing rate limiting to prevent abuse
| Feature | HyperTCP | WebSocket |
|---|---|---|
| Protocol Layer | Pure TCP | HTTP + WebSocket |
| Overhead | Minimal | Higher (HTTP headers) |
| Complexity | Low | Medium |
| Browser Support | Requires TCP library | Native |
| Real-time Performance | Excellent | Good |
| Authentication | Built-in | Custom implementation |
- Encryption Support: Add TLS/SSL encryption
- Message Compression: Implement payload compression for bandwidth optimization
- Priority Queuing: Add message priority levels
- Quality of Service: Implement QoS levels for critical messages
- Clustering: Support for distributed server clusters
- Persistence: Add message persistence for offline clients