首页
技术知识库
Task工作计划
网站简介
DON框架
后台管理
文章分类
JAVA
框架知识
操作系统
容器相关
数据库层
优化技术
界面编程
网络编程
开发工具
GO语言
其他
读书随笔
观影随笔
每日随笔
APP
netty4.0代码模板
所属分类
:[网络编程] |
创建时间
:2014-05-17 |
文章属性
:原创 |
文章来源
:http://windfly.cn |
作者
:windfly
##服务端代码 <pre > package cn.windfly.util.netty; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.serialization.ClassResolvers; import io.netty.handler.codec.serialization.ObjectDecoder; import io.netty.handler.codec.serialization.ObjectEncoder; import io.netty.handler.timeout.IdleStateHandler; import java.util.logging.Logger; import cn.windfly.util.PropertiesUtil; import java.util.logging.Level; public class NettyServer { private final int socketLinkTimeout = PropertiesUtil.getInt("socket.link.timeout"); private final int socketTestTime = PropertiesUtil.getInt("socket.test.time"); private static final Logger logger = Logger.getLogger(NettyServer.class.getName()); private final int port; public NettyServer(int port) { this.port = port; } public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); final NettyServer nettyServer = this; try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel arg0) throws Exception { arg0.pipeline() .addLast(new IdleStateHandler(socketTestTime,0 , socketLinkTimeout), new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)), new ServerHandle(nettyServer)); } }).childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); logger.log(Level.INFO, "socket服务端启动,监听端口:{0}", port); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } } </pre> ##客户端代码 <pre> package cn.windfly.util.netty; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.serialization.ClassResolvers; import io.netty.handler.codec.serialization.ObjectDecoder; import io.netty.handler.codec.serialization.ObjectEncoder; import io.netty.handler.timeout.IdleStateHandler; import java.util.logging.Logger; import cn.windfly.util.PropertiesUtil; import java.util.logging.Level; public class NettyClient { private final int socketLinkTimeout = PropertiesUtil.getInt("socket.link.timeout"); private final int socketTestTime = PropertiesUtil.getInt("socket.test.time"); String ip = "localhost"; int port = 90; Channel channel; EventLoopGroup workgGroup = new NioEventLoopGroup(); ChannelFuture lastChannelFuture; public NettyClient(String ip, int port) { this.ip = ip; this.port = port; } public void connect() { final ClentHandel clentHandel =new ClentHandel(this); Bootstrap b = new Bootstrap(); b.group(workgGroup) .channel(NioSocketChannel.class) .remoteAddress(ip, port) .option(ChannelOption.SO_KEEPALIVE, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel arg0) throws Exception { arg0.pipeline() .addLast(new IdleStateHandler(socketTestTime,0 , socketLinkTimeout), new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)), clentHandel); } }); try { channel = b.connect().sync().channel(); } catch (InterruptedException e) { logger.severe(e.getMessage()); } } public void send(Object content) { lastChannelFuture = channel.writeAndFlush(content); logger.log(Level.INFO, "发送信息:{0}", content); } public void close() { try { lastChannelFuture.sync(); workgGroup.shutdownGracefully(); } catch (InterruptedException e) { logger.severe(e.getMessage()); } } static final Logger logger = Logger.getLogger(NettyClient.class.getName()); } </pre> ##服务端处理代码 <pre> package cn.windfly.util.netty; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleStateEvent; import java.net.SocketAddress; import java.util.logging.Level; import java.util.logging.Logger; public class ServerHandle extends SimpleChannelInboundHandler<Object> { static final Logger log = Logger.getLogger(ServerHandle.class.getName()); NettyServer nettyServer; public ServerHandle(NettyServer nettyServer) { this.nettyServer = nettyServer; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { log.severe(cause.getMessage()); ctx.close(); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); log.log(Level.INFO, "{0} server channelInactive", ctx.channel().remoteAddress()); } @Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { super.channelUnregistered(ctx); log.log(Level.INFO, "{0} server channelUnregistered", ctx.channel().remoteAddress()); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { SocketAddress remoteAddress = ctx.channel().remoteAddress(); log.log(Level.INFO, "建立连接,来源:{0}", remoteAddress.toString()); } @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { log.log(Level.INFO, "{0} 收到信息:{1}", new Object[]{ctx.channel().remoteAddress(), msg.toString()}); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (!(evt instanceof IdleStateEvent)) { return; } IdleStateEvent e = (IdleStateEvent) evt; if (e.state() == IdleState.READER_IDLE) { log.log(Level.INFO, "{0} 发送心跳包", ctx.channel().remoteAddress()); ctx.writeAndFlush("TestLink"); }else if (e.state() == IdleState.ALL_IDLE) { log.log(Level.INFO, "{0} 长时间无数据,判断为连接断开", ctx.channel().remoteAddress()); ctx.close(); } } } </pre> ## 客户端处理代码 <pre> package cn.windfly.util.netty; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.EventLoop; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleStateEvent; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import cn.windfly.util.PropertiesUtil; import java.util.logging.Level; public class ClentHandel extends SimpleChannelInboundHandler<String> { int reconnectSecond = PropertiesUtil.getInt("socket.client.reconnect"); NettyClient client; public ClentHandel(NettyClient client) { this.client = client; } static final Logger logger = Logger.getLogger(ClentHandel.class.getSimpleName()); @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { logger.log(Level.INFO, "收到信息:{0}", msg); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { logger.info("连接上服务器"); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { logger.info("连接断开"); } @Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { logger.log(Level.INFO, "{0}秒后自动重连", reconnectSecond); final EventLoop loop = ctx.channel().eventLoop(); loop.schedule(new Runnable() { @Override public void run() { client.connect(); } }, reconnectSecond, TimeUnit.SECONDS); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (!(evt instanceof IdleStateEvent)) { return; } IdleStateEvent e = (IdleStateEvent) evt; if (e.state() == IdleState.READER_IDLE) { logger.info("发送心跳包"); ctx.writeAndFlush("TestLink"); }else if (e.state() == IdleState.ALL_IDLE) { logger.info("长时间无数据,判断为连接断开"); ctx.close(); } } } </pre>
返回