Netty demo 时间查询
2015-09-10 11:16
253 查看
Netty实现简单的时间查询服务
package com.jiepu.netty2.time; 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; /** * server 有粘包问题 * * @author xwalker */ public class TimeServer { public void bind(int port) throws Exception { // 服务器线程组 用于网络事件的处理 一个用于服务器接收客户端的连接 // 另一个线程组用于处理SocketChannel的网络读写 EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { // NIO服务器端的辅助启动类 降低服务器开发难度 ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class)// 类似NIO中serverSocketChannel .option(ChannelOption.SO_BACKLOG, 1024)// 配置TCP参数 .childHandler(new ChildChannelHandler());// 最后绑定I/O事件的处理类 // 处理网络IO事件 // 服务器启动后 绑定监听端口 同步等待成功 主要用于异步操作的通知回调 回调处理用的ChildChannelHandler ChannelFuture f = serverBootstrap.bind(port).sync(); System.out.println("timeServer启动"); // 等待服务端监听端口关闭 f.channel().closeFuture().sync(); } finally { // 优雅退出 释放线程池资源 bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); System.out.println("服务器优雅的释放了线程资源..."); } } /** * 网络事件处理器 */ private class ChildChannelHandler extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new TimeServerHandler()); } } public static void main(String[] args) throws Exception { int port = 8000; new TimeServer().bind(port); } }
package com.jiepu.netty2.time; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import java.util.Date; /** * server端网络IO事件处理 * @author xwalker * */ public class TimeServerHandler extends ChannelHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("服务器读取到客户端请求..."); ByteBuf buf=(ByteBuf) msg; byte[] req=new byte[buf.readableBytes()]; buf.readBytes(req); String body=new String(req,"UTF-8"); System.out.println("the time server receive order:"+body); String curentTime="QUERY TIME ORDER".equalsIgnoreCase(body)?new Date(System.currentTimeMillis()).toString():"BAD ORDER"; ByteBuf resp=Unpooled.copiedBuffer(curentTime.getBytes()); ctx.write(resp); System.out.println("服务器做出了响应"); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); System.out.println("服务器readComplete 响应完成"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); System.out.println("服务器异常退出"+cause.getMessage()); } }
package com.jiepu.netty2.time; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import java.util.logging.Logger; /** * Client 网络IO事件处理 * @author xwalker * */ public class TimeClientHandler extends ChannelHandlerAdapter { private static final Logger logger=Logger.getLogger(TimeClientHandler.class.getName()); private ByteBuf firstMessage; public TimeClientHandler(){ byte[] req ="QUERY TIME ORDER".getBytes(); firstMessage=Unpooled.buffer(req.length); firstMessage.writeBytes(req); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(firstMessage); System.out.println("客户端active"); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("客户端收到服务器响应数据"); ByteBuf buf=(ByteBuf) msg; byte[] req=new byte[buf.readableBytes()]; buf.readBytes(req); String body=new String(req,"UTF-8"); System.out.println("Now is:"+body); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); System.out.println("客户端收到服务器响应数据处理完成"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.warning("Unexpected exception from downstream:"+cause.getMessage()); ctx.close(); System.out.println("客户端异常退出"); } }
package com.jiepu.netty2.time; import io.netty.bootstrap.Bootstrap; 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; /** * client 存在TCP粘包问题 * @author xwlaker * Netty实现简单的时间查询服务 * http://www.oschina.net/code/snippet_374_44686 * */ public class TimeClient { /** * 连接服务器 * @param port * @param host * @throws Exception */ public void connect(int port, String host) throws Exception { //配置客户端NIO线程组 EventLoopGroup group = new NioEventLoopGroup(); try { //客户端辅助启动类 对客户端配置 Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new TimeClientHandler()); } }); //异步链接服务器 同步等待链接成功 ChannelFuture f = b.connect(host, port).sync(); //等待链接关闭 f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); System.out.println("客户端优雅的释放了线程资源..."); } } public static void main(String[] args) throws Exception { new TimeClient().connect(8000, "127.0.0.1"); } }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jiepu</groupId> <artifactId>netty2</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>netty2</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId><!-- netty-all --> <version>5.0.0.Alpha1</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> </project>
相关文章推荐
- ssh 设置超时时间 Write failed: Broken pipe
- Unity 游戏开发技巧集锦之材质的应用的创建反射材质
- PHP中返回上一页的问题
- 4G时代的移动运营商们
- ios 获取应用唯一标识
- ios 获取应用唯一标识
- SQL 2000挂马的批量替换
- getchar()函数getch()函数区别?
- 感谢生活中所遇到的人。
- ubuntu解压缩命令(转+收藏)
- 什么是iBeacons
- golang rabbitmq实践(啰嗦)
- ios应用数据存储方式(偏好设置)
- 位带操作在stm32中的C语言实现
- java常见内存溢出(OOM)解决方案
- 在php中使输出的alert内容换行
- netty Demo 实例
- MBR&GPT硬盘分区类型&属性详解(Win下更改/设置OEM/恢复分区方法)
- 我在学习爬虫(二)
- 系统调用read,write和标准库fread,fwrite的区别