1.extends ChannelInboundHandlerAdapter
代码如下(示例):
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
/**
* server端自己的业务处理类
*/
@ChannelHandler.Sharable
public class MyEchoServerHandle extends ChannelInboundHandlerAdapter {
/*
* 客户端读到数据以后就会执行
* */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf byteBuf = (ByteBuf) msg;
System.out.println("server accept: "+byteBuf.toString(CharsetUtil.UTF_8));
ctx.write(byteBuf);
}
/**
* 服务器端读完以后的处理
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
.addListener(ChannelFutureListener.CLOSE);
}
/**
* 发生异常后的处理
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
2.server代码
代码如下(示例):
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.net.InetSocketAddress;
public class MyEchoServer {
private int port;
public MyEchoServer(int port) {
this.port = port;
}
public void start() throws InterruptedException {
final MyEchoServerHandle handle = new MyEchoServerHandle();
EventLoopGroup group = new NioEventLoopGroup();
try{
ServerBootstrap strap = new ServerBootstrap();
strap.group(group)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) throws Exception {
/*添加到该子channel的pipeline的尾部*/
ch.pipeline().addLast(handle);
}
});
ChannelFuture future = strap.bind().sync();
future.channel().closeFuture().sync();
}finally {
group.shutdownGracefully().sync();/*优雅关闭线程组*/
}
}
public static void main(String[] args) throws InterruptedException {
MyEchoServer myEchoServer = new MyEchoServer(9090);
System.out.println("服务器启动-------------");
myEchoServer.start();
System.out.println("服务器关闭-------------");
}
}