Package com.framed.core.remote
Class NioTcpTransport
java.lang.Object
com.framed.core.remote.NioTcpTransport
- All Implemented Interfaces:
Transport
A
Transport implementation using Java NIO for TCP-based communication.
This class provides non-blocking I/O for message exchange between components,
services or devices using a simple JSON-based protocol.
Messages are framed by newline characters and contain
fields for address, payload, and type.
Features:
- Non-blocking server using
SelectorandServerSocketChannel. - Handles multiple clients concurrently.
- Dispatches messages to registered handlers asynchronously via a worker pool.
- Supports point-to-point (
send(java.lang.String, int, java.lang.String, java.lang.Object)) and broadcast (publish(java.lang.String, int, java.lang.String, java.lang.Object)) messaging.
Message Format:
{
"address": "topic.name",
"payload": "data",
"type": "send" | "publish"
}
Example usage:
NioTcpTransport transport = new NioTcpTransport(8080);
transport.register("sensor.data", msg -> System.out.println("Received: " + msg));
transport.start();
transport.send("localhost", 8080, "sensor.data", "Hello");
Note: Always call shutdown() to release resources when done.
-
Constructor Summary
ConstructorsConstructorDescriptionNioTcpTransport(int port) Creates a new NIO TCP transport bound to the specified port. -
Method Summary
Modifier and TypeMethodDescriptionvoidPublishes a message to all subscribers of the specified address.voidRegisters a handler for messages received on the specified address.voidSends a message to the first subscriber of the specified address.voidshutdown()Shuts down the transport, closing the selector, server channel, and worker pool.voidstart()Starts the transport event loop in a background thread.
-
Constructor Details
-
NioTcpTransport
Creates a new NIO TCP transport bound to the specified port.- Parameters:
port- the TCP port to listen on- Throws:
IOException- if the server socket or selector cannot be initialized
-
-
Method Details
-
start
public void start()Starts the transport event loop in a background thread.Accepts new connections and reads incoming messages asynchronously.
-
send
Sends a message to the first subscriber of the specified address. -
publish
Publishes a message to all subscribers of the specified address. -
shutdown
public void shutdown()Shuts down the transport, closing the selector, server channel, and worker pool. -
register
Registers a handler for messages received on the specified address.
-