Created
July 18, 2017 08:50
-
-
Save pfreixes/13fedf2a589c260e6c7c64ae73653bb1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test; | |
import io.netty.bootstrap.Bootstrap; | |
import io.netty.buffer.ByteBuf; | |
import io.netty.channel.*; | |
import io.netty.channel.nio.NioEventLoopGroup; | |
import io.netty.channel.socket.SocketChannel; | |
import io.netty.channel.socket.nio.NioSocketChannel; | |
import java.nio.charset.Charset; | |
public class NettyTest { | |
public static void main(String[] args) throws Exception { | |
String host = args[0]; | |
int port = Integer.parseInt(args[1]); | |
int sleepMillis = Integer.parseInt(args[2]); | |
NioEventLoopGroup workerGroup = new NioEventLoopGroup(); | |
try { | |
Bootstrap b = new Bootstrap() | |
.group(workerGroup) | |
.channel(NioSocketChannel.class) | |
.handler(new ChannelInitializer<SocketChannel>() { | |
@Override | |
public void initChannel(SocketChannel ch) throws Exception { | |
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { | |
@Override | |
public void channelActive(final ChannelHandlerContext ctx) { | |
System.out.println("channelActive"); | |
try { | |
System.out.println("Sleeping..."); | |
Thread.sleep(sleepMillis); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
@Override | |
public void channelRead(ChannelHandlerContext ctx, Object msg) { | |
System.out.println("channelRead"); | |
ByteBuf m = (ByteBuf) msg; | |
try { | |
int bytesAvaliable = m.readableBytes(); | |
System.out.println(bytesAvaliable + " readable bytes in response buffer"); | |
m.readBytes(bytesAvaliable); | |
System.out.println(m.getCharSequence(0, bytesAvaliable, Charset.defaultCharset())); | |
ctx.close(); | |
} finally { | |
m.release(); | |
} | |
} | |
@Override | |
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { | |
cause.printStackTrace(); | |
ctx.close(); | |
} | |
}); | |
} | |
}); | |
// Start the client. | |
ChannelFuture f = b.connect(host, port).sync(); | |
// Wait until the connection is closed. | |
f.channel().closeFuture().sync(); | |
} finally { | |
workerGroup.shutdownGracefully(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output