1. 使用示例
public class EchoServer {
private final int port;
public EchoServer ( int port) {
this . port = port;
}
public void start ( ) throws InterruptedException {
final EchoServerHandler serverHandler = new EchoServerHandler ( ) ;
EventLoopGroup group = new NioEventLoopGroup ( ) ;
try {
ServerBootstrap b = new ServerBootstrap ( ) ;
b. group ( group)
. channel ( NioServerSocketChannel . class )
. localAddress ( new InetSocketAddress ( port) )
. childHandler ( new ChannelInitializer < SocketChannel > ( ) {
@Override
protected void initChannel ( SocketChannel ch) {
ch. pipeline ( ) . addLast ( serverHandler) ;
}
} ) ;
ChannelFuture f = b. bind ( ) . sync ( ) ;
f. channel ( ) . closeFuture ( ) . sync ( ) ;
} finally {
group. shutdownGracefully ( ) . sync ( ) ;
}
}
public static void main ( String [ ] args) throws InterruptedException {
EchoServer echoServer = new EchoServer ( 9999 ) ;
echoServer. start ( ) ;
}
}
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead ( ChannelHandlerContext ctx, Object msg) {
ByteBuf in = ( ByteBuf ) msg;
System . out. println ( "Hello Client" ) ;
ctx. writeAndFlush ( in) ;
}
@Override
public void exceptionCaught ( ChannelHandlerContext ctx, Throwable cause) {
cause. printStackTrace ( ) ;
ctx. close ( ) ;
}
}
public class EchoClient {
private final int port;
private final String host;
public EchoClient ( int port, String host) {
this . port = port;
this . host = host;
}
public void start ( ) throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup ( ) ;
try {
Bootstrap b = new Bootstrap ( ) ;
b. group ( group)
. channel ( NioSocketChannel . class )
. remoteAddress ( new InetSocketAddress ( host, port) )
. handler ( new ChannelInitializer < SocketChannel > ( ) {
@Override
protected void initChannel ( SocketChannel ch) {
ch. pipeline ( ) . addLast ( new EchoClientHandler ( ) ) ;
}
} ) ;
ChannelFuture f = b. connect ( ) . sync ( ) ;
f. channel ( ) . closeFuture ( ) . sync ( ) ;
} finally {
group. shutdownGracefully ( ) . sync ( ) ;
}
}
public static void main ( String [ ] args) throws InterruptedException {
new EchoClient ( 9999 , "127.0.0.1" ) . start ( ) ;
}
}
public class EchoClientHandler extends SimpleChannelInboundHandler < ByteBuf > {
@Override
protected void channelRead0 ( ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
System . out. println ( "client Accept:" + msg. toString ( CharsetUtil . UTF_8) ) ;
ctx. close ( ) ;
}
@Override
public void channelActive ( ChannelHandlerContext ctx) throws Exception {
ctx. writeAndFlush ( Unpooled . copiedBuffer ( "Hello,Netty" , CharsetUtil . UTF_8) ) ;
}
}