netty應用的領域
1分佈式進程通信
例如: hadoop、dubbo、akka等具有分佈式功能的框架,底層RPC通信都是基於netty實現的,這些框架使用的版本通常都還在用netty3.x
2、遊戲服務器開發
最新的遊戲服務器有部分公司可能已經開始採用netty4.x 或 netty5.x
代碼示例
public class Server {
public static void main(String[] args) {
ServerBootstrap serverBootstrap = new ServerBootstrap();
ExecutorService boss = Executors.newCachedThreadPool();
ExecutorService worker = Executors.newCachedThreadPool();
//設置NioSocket工廠
serverBootstrap.setFactory(new NioServerSocketChannelFactory(boss,worker));
//設置管道工廠
serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
//創建管道
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("ServerHandler", new ServerHandler());
return pipeline;
}
});
serverBootstrap.bind(new InetSocketAddress(8000));
System.out.println("NIOServer started!!!!!!!!!!!");
}
}
public class ServerHandler extends SimpleChannelHandler{
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
System.out.println("channelClosed");
super.channelClosed(ctx, e);
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent event)
throws Exception {
System.out.println("channelConnected"+event.getChannel().getRemoteAddress());
super.channelConnected(ctx, event);
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
System.out.println("channelDisconnected");
super.channelDisconnected(ctx, e);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
System.out.println("exceptionCaught");
super.exceptionCaught(ctx, e);
}
@Override
public void messageReceived(ChannelHandlerContext context, MessageEvent message)
throws Exception {
String buffer = (String) message.getMessage();
System.out.println("received message:"+buffer);
ChannelBuffer buffer2 = ChannelBuffers.copiedBuffer("Hi".getBytes());
context.getChannel().write(buffer2);
super.messageReceived(context, message);
}
}