use of com.bonree.brfs.common.net.tcp.TokenMessage in project BRFS by zhangnianli.
the class AsyncTcpClientGroup method createClient.
@Override
public TcpClient<BaseMessage, BaseResponse> createClient(TcpClientConfig config, Executor executor) throws InterruptedException {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator());
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectTimeoutMillis());
if (executor == null) {
executor = new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
};
}
AsyncTcpClient client = new AsyncTcpClient(executor);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new IdleStateHandler(0, DEFAULT_WRITE_IDLE_TIMEOUT_SECONDS, 0)).addLast(new BaseMessageEncoder()).addLast(new BaseResponseDecoder()).addLast(new SimpleChannelInboundHandler<TokenMessage<BaseResponse>>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, TokenMessage<BaseResponse> msg) throws Exception {
client.handle(msg.messageToken(), msg.message());
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent e = (IdleStateEvent) evt;
if (e.state() == IdleState.WRITER_IDLE) {
ctx.writeAndFlush(new BaseMessage(-1));
}
}
}
});
}
});
ChannelFuture future = bootstrap.connect(config.remoteAddress()).sync();
if (!future.isSuccess()) {
return null;
}
Channel channel = future.channel();
channelList.add(channel);
channel.closeFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
channelList.remove(channel);
}
});
LOG.info("create tcp client for {}", config.remoteAddress());
client.attach(channel);
return client;
}
use of com.bonree.brfs.common.net.tcp.TokenMessage in project BRFS by zhangnianli.
the class AbstractTcpClient method sendMessage.
@Override
public void sendMessage(S msg, ResponseHandler<R> handler) throws Exception {
Preconditions.checkNotNull(msg);
Preconditions.checkNotNull(handler);
final int token = tokenMaker.getAndIncrement() & Integer.MAX_VALUE;
handlers.put(token, handler);
channel.writeAndFlush(new TokenMessage<S>() {
@Override
public int messageToken() {
return token;
}
@Override
public S message() {
return msg;
}
}).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
handlers.remove(token);
executor.execute(new Runnable() {
@Override
public void run() {
handler.error(new Exception("send message of token[" + token + "] error"));
}
});
channel.close();
}
}
});
}
Aggregations