use of services.moleculer.transporter.tcp.TcpReader in project moleculer-java by moleculer-java.
the class TcpTransporter method connect.
@Override
public void connect() {
try {
// Create reader and writer
disconnect();
reader = new TcpReader(this);
writer = new TcpWriter(this);
// Disable offline timeout when use host list
if (urls != null && urls.length > 0) {
offlineTimeout = 0;
nodes.clear();
for (String url : urls) {
int i = url.indexOf("://");
if (i > -1 && i < url.length() - 4) {
url = url.substring(i + 3);
}
url = url.replace('/', ':');
String[] parts = url.split(":");
if (parts.length < 3) {
logger.warn("Invalid URL format (" + url + ")! Valid syntax is \"tcp://host:port/nodeID\" or \"host:port/nodeID\"!");
continue;
}
int port;
try {
port = Integer.parseInt(parts[1]);
} catch (Exception e) {
logger.warn("Invalid URL format (" + url + ")! Valid syntax is \"tcp://host:port/nodeID\" or \"host:port/nodeID\"!");
continue;
}
String sender = parts[2];
if (sender.equals(nodeID)) {
// TCP server's port (port in URL list)
this.port = port;
continue;
}
String host = parts[0];
nodes.put(sender, new NodeDescriptor(sender, useHostname, host, port));
}
} else if (offlineTimeout > 0 && offlineTimeout < 15) {
offlineTimeout = 15;
}
// Process basic properties (eg. "prefix")
heartbeatTimeout = 0;
heartbeatInterval = 0;
// Start TCP server
reader.connect();
currentPort = reader.getCurrentPort();
// Create descriptor of current node
Tree info = registry.getDescriptor();
info.put("port", currentPort);
info.put("seq", "0");
cachedDescriptor = new NodeDescriptor(nodeID, useHostname, true, info);
// Start data writer (TCP client)
writer.connect();
// TCP + UDP mode ("zero config")
if (urls == null || urls.length == 0) {
locator = new UDPLocator(nodeID, this, scheduler);
locator.connect();
}
// Start gossiper
gossiperTimer = scheduler.scheduleWithFixedDelay(this::sendGossipRequest, gossipPeriod, gossipPeriod, TimeUnit.SECONDS);
// Start timeout checker's timer
if (checkTimeoutTimer == null && offlineTimeout > 0) {
int period = Math.max(offlineTimeout / 3, 10);
checkTimeoutTimer = scheduler.scheduleAtFixedRate(this::checkTimeouts, period, period, TimeUnit.SECONDS);
}
// Ok, transporter started
logger.info("Message receiver started on tcp://" + getHostName() + ':' + currentPort + ".");
} catch (Exception cause) {
String msg = cause.getMessage();
if (msg == null || msg.isEmpty()) {
msg = "Unable to start TCP transporter!";
} else if (!msg.endsWith("!") && !msg.endsWith(".")) {
msg += "!";
}
logger.warn(msg);
reconnect();
}
}
Aggregations