
org.bdware.irp3.client.ClientChannel Maven / Gradle / Ivy
package org.bdware.irp3.client;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.irp3.codec.MessageBody;
import java.net.URI;
import java.net.URISyntaxException;
public class ClientChannel {
final Bootstrap b = new Bootstrap();
private final ClientHandler handler;
static Logger LOGGER = LogManager.getLogger(ClientChannel.class);
private static final int DefaultTimeout = 5;
private ClientBootstrapInitializer clientBootstrapInitializer;
public ClientChannel(ClientConfig config) {
handler = new ClientHandler();
clientBootstrapInitializer = ClientBootstrapInitializerFactory.createServerBootstrapInitializer(config);
clientBootstrapInitializer.init(b,handler);
}
public void sendMessage(MessageBody message, ResultCallback cb) {
handler.sendMessage(message, cb, 5);
}
static class SyncCallback implements ResultCallback {
private MessageBody response;
@Override
public synchronized void onResult(MessageBody message) {
response = message;
this.notifyAll();
}
}
public MessageBody sendMessageSync(MessageBody msg) {
return sendMessageSync(msg, DefaultTimeout);
}
public MessageBody sendMessageSync(MessageBody msg, int timeoutInSeconds) {
SyncCallback rcb = new SyncCallback();
handler.sendMessage(msg, rcb, timeoutInSeconds);
synchronized (rcb) {
try {
rcb.wait(timeoutInSeconds * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (rcb.response == null)
return null;
return rcb.response;
}
public void connect(URI uri, IrpClient irpClient) throws URISyntaxException {
LOGGER.info("[URI Parse]scheme:" + uri.getScheme() + " host: " + uri.getHost() + " port: " + uri.getPort());
try {
Channel channel = b.connect(uri.getHost(), uri.getPort()).sync().channel();
handler.setChannel(channel);
handler.setClient(irpClient);
} catch (Exception e) {
e.printStackTrace();
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy