use of io.netty.channel.ChannelPromise in project MinecraftForge by MinecraftForge.
the class PacketLoggingHandler method register.
public static void register(NetworkManager manager) {
ChannelPipeline pipeline = manager.channel().pipeline();
final EnumPacketDirection direction = manager.getDirection();
if (manager.isLocalChannel()) {
pipeline.addBefore("packet_handler", "splitter", new SimpleChannelInboundHandler<Packet<?>>() {
String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: C->S" : "CLIENT: S->C");
@Override
protected void channelRead0(ChannelHandlerContext ctx, Packet<?> msg) throws Exception {
PacketBuffer buf = new PacketBuffer(Unpooled.buffer());
msg.writePacketData(buf);
FMLLog.log(Level.DEBUG, "%s %s:\n%s", prefix, msg.getClass().getSimpleName(), ByteBufUtils.getContentDump(buf));
ctx.fireChannelRead(msg);
}
});
pipeline.addBefore("splitter", "prepender", new ChannelOutboundHandlerAdapter() {
String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: S->C" : "CLIENT: C->S");
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof Packet<?>) {
PacketBuffer buf = new PacketBuffer(Unpooled.buffer());
((Packet<?>) msg).writePacketData(buf);
FMLLog.log(Level.DEBUG, "%s %s:\n%s", prefix, msg.getClass().getSimpleName(), ByteBufUtils.getContentDump(buf));
}
ctx.write(msg, promise);
}
});
} else {
pipeline.replace("splitter", "splitter", new NettyVarint21FrameDecoder() {
String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: C->S" : "CLIENT: S->C");
@Override
protected void decode(ChannelHandlerContext context, ByteBuf input, List<Object> output) throws Exception {
super.decode(context, input, output);
Iterator<Object> itr = output.iterator();
while (itr.hasNext()) {
ByteBuf pkt = (ByteBuf) itr.next();
pkt.markReaderIndex();
FMLLog.log(Level.DEBUG, "%s:\n%s", prefix, ByteBufUtils.getContentDump(pkt));
pkt.resetReaderIndex();
}
}
});
pipeline.replace("prepender", "prepender", new NettyVarint21FrameEncoder() {
String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: S->C" : "CLIENT: C->S");
@Override
protected void encode(ChannelHandlerContext context, ByteBuf input, ByteBuf output) throws Exception {
input.markReaderIndex();
FMLLog.log(Level.DEBUG, "%s:\n%s", prefix, ByteBufUtils.getContentDump(input));
input.resetReaderIndex();
super.encode(context, input, output);
}
});
}
}
use of io.netty.channel.ChannelPromise in project netty by netty.
the class HttpResponseHandler method channelRead0.
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
Integer streamId = msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
if (streamId == null) {
System.err.println("HttpResponseHandler unexpected message received: " + msg);
return;
}
Entry<ChannelFuture, ChannelPromise> entry = streamidPromiseMap.get(streamId);
if (entry == null) {
System.err.println("Message received for unknown stream id " + streamId);
} else {
// Do stuff with the message (for now just print it)
ByteBuf content = msg.content();
if (content.isReadable()) {
int contentLength = content.readableBytes();
byte[] arr = new byte[contentLength];
content.readBytes(arr);
System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8));
}
entry.getValue().setSuccess();
}
}
use of io.netty.channel.ChannelPromise in project netty by netty.
the class HttpResponseHandler method awaitResponses.
/**
* Wait (sequentially) for a time duration for each anticipated response
*
* @param timeout Value of time to wait for each response
* @param unit Units associated with {@code timeout}
* @see HttpResponseHandler#put(int, io.netty.channel.ChannelFuture, io.netty.channel.ChannelPromise)
*/
public void awaitResponses(long timeout, TimeUnit unit) {
Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet().iterator();
while (itr.hasNext()) {
Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
ChannelFuture writeFuture = entry.getValue().getKey();
if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
}
if (!writeFuture.isSuccess()) {
throw new RuntimeException(writeFuture.cause());
}
ChannelPromise promise = entry.getValue().getValue();
if (!promise.awaitUninterruptibly(timeout, unit)) {
throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
}
if (!promise.isSuccess()) {
throw new RuntimeException(promise.cause());
}
System.out.println("---Stream id: " + entry.getKey() + " received---");
itr.remove();
}
}
use of io.netty.channel.ChannelPromise in project netty by netty.
the class LocalChannelTest method testClosePeerInWritePromiseCompleteSameEventLoopPreservesOrder.
@Test
public void testClosePeerInWritePromiseCompleteSameEventLoopPreservesOrder() throws InterruptedException {
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
final CountDownLatch messageLatch = new CountDownLatch(2);
final CountDownLatch serverChannelLatch = new CountDownLatch(1);
final ByteBuf data = Unpooled.wrappedBuffer(new byte[1024]);
final AtomicReference<Channel> serverChannelRef = new AtomicReference<Channel>();
try {
cb.group(sharedGroup).channel(LocalChannel.class).handler(new TestHandler());
sb.group(sharedGroup).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg.equals(data)) {
ReferenceCountUtil.safeRelease(msg);
messageLatch.countDown();
} else {
super.channelRead(ctx, msg);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
messageLatch.countDown();
super.channelInactive(ctx);
}
});
serverChannelRef.set(ch);
serverChannelLatch.countDown();
}
});
Channel sc = null;
Channel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).syncUninterruptibly().channel();
// Connect to the server
cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
assertTrue(serverChannelLatch.await(5, SECONDS));
final Channel ccCpy = cc;
// Make sure a write operation is executed in the eventloop
cc.pipeline().lastContext().executor().execute(new Runnable() {
@Override
public void run() {
ChannelPromise promise = ccCpy.newPromise();
promise.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
serverChannelRef.get().close();
}
});
ccCpy.writeAndFlush(data.retainedDuplicate(), promise);
}
});
assertTrue(messageLatch.await(5, SECONDS));
assertFalse(cc.isOpen());
assertFalse(serverChannelRef.get().isOpen());
} finally {
closeChannel(cc);
closeChannel(sc);
}
} finally {
data.release();
}
}
use of io.netty.channel.ChannelPromise in project netty by netty.
the class LocalChannelTest method testConnectFutureBeforeChannelActive.
@Test(timeout = 3000)
public void testConnectFutureBeforeChannelActive() throws Exception {
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
cb.group(group1).channel(LocalChannel.class).handler(new ChannelInboundHandlerAdapter());
sb.group(group2).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new TestHandler());
}
});
Channel sc = null;
Channel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).sync().channel();
cc = cb.register().sync().channel();
final ChannelPromise promise = cc.newPromise();
final Promise<Void> assertPromise = cc.eventLoop().newPromise();
cc.pipeline().addLast(new TestHandler() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// Ensure the promise was done before the handler method is triggered.
if (promise.isDone()) {
assertPromise.setSuccess(null);
} else {
assertPromise.setFailure(new AssertionError("connect promise should be done"));
}
}
});
// Connect to the server
cc.connect(sc.localAddress(), promise).sync();
assertPromise.syncUninterruptibly();
assertTrue(promise.isSuccess());
} finally {
closeChannel(cc);
closeChannel(sc);
}
}
Aggregations