Vertx TCP saves your effort greatly to write a TCP application - baoyingwang/LibrariesEvaluation GitHub Wiki
Introduction
Here is the detail of how to write - http://vertx.io/docs/vertx-core/java/#_writing_tcp_servers_and_clients
I still have to highlight something, which will help you setup it quickly.
setup the RecordParser, to split each incoming message.
The official doc has mentioned, but does not give clearly link - http://vertx.io/docs/vertx-core/java/#_record_parser
Here is an example of server with RecordParser. Similar code for client.
NetServerOptions options = new NetServerOptions().setTcpNoDelay(true);
NetServer server = _vertx.createNetServer(options);
server.connectHandler(socket -> {
//http://vertx.io/docs/vertx-core/java/#_record_parser
final RecordParser parser = RecordParser.newDelimited(vertxTCPDelimiter, buffer -> {
handleMessage(buffer, socket);
});
socket.handler(buffer -> {
parser.handle(buffer);
});
socket.closeHandler(v -> {
String clientCompID = _liveClientCompIDs.inverse().remove(socket);
log.info("The socket has been closed for:{}", clientCompID);
});
});
server.listen(_vertx_tcp_port, "localhost", res -> {
if (res.succeeded()) {
log.info("Vertx TCP Server is now listening on :{}", _vertx_tcp_port);
} else {
log.error("Failed to bind:{}!",_vertx_tcp_port);
}
});
Server code is copied from https://github.com/baoyingwang/OrderBook/blob/master/src/main/java/baoying/orderbook/app/MatchingEngineVertxWrapper.java For client code - see https://github.com/baoyingwang/OrderBook/blob/master/src/main/java/baoying/orderbook/testtool/vertx/VertxClientRoundBatch.java
Error Handling
Re-connection
For now(vertx 3.5 / Feb, 2018), it only supports reconnect attempts for the initial connection. If you hope to reconnect after that, you have to introduce your own logic. You can do that to write some code on the closeHandler(there is a such handler in above sample)
A client can be configured to automatically retry connecting to the server in the event that it cannot connect. This is configured with setReconnectInterval and setReconnectAttempts.
NOTE
Currently Vert.x will not attempt to reconnect if a connection fails, reconnect attempts and interval only apply to creating initial connections.
NetClientOptions options = new NetClientOptions().
setReconnectAttempts(10).
setReconnectInterval(500);
NetClient client = vertx.createNetClient(options);
By default, multiple connection attempts are disabled.
Copied from http://vertx.io/docs/vertx-core/java/#_configuring_connection_attempts
TODO other error handlings
The socket support exceptionHandler More effort is required to confirm when/why use it.
- see : http://vertx.io/docs/vertx-core/java/#_readstream
- see : http://vertx.io/docs/vertx-core/java/#_writestream
Anyway, it is always good idea to log warn at least, on exceptionHandler!!!