diff --git a/pom.xml b/pom.xml index 625c69e..4077b45 100644 --- a/pom.xml +++ b/pom.xml @@ -24,6 +24,11 @@ 1.6 + + io.netty + netty-all + 5.0.0.Alpha2 + diff --git a/src/main/java/com/JVM/heap/HeapGCTest.java b/src/main/java/com/JVM/heap/HeapGCTest.java index f001e5b..4d975c2 100644 --- a/src/main/java/com/JVM/heap/HeapGCTest.java +++ b/src/main/java/com/JVM/heap/HeapGCTest.java @@ -1,4 +1,4 @@ -package main.java.com.JVM.heap; +package com.ufclub.ljs.autoInvest.model.AutoInvestSettingcom.JVM.heap; /** * Java GC测试 diff --git a/src/main/java/com/JVM/perm/PermGengc.java b/src/main/java/com/JVM/perm/PermGengc.java index 7d5f04e..d1fb6e5 100644 --- a/src/main/java/com/JVM/perm/PermGengc.java +++ b/src/main/java/com/JVM/perm/PermGengc.java @@ -1,4 +1,4 @@ -package main.java.com.JVM.perm; +package com.ufclub.ljs.autoInvest.model.AutoInvestSettingcom.JVM.perm; /** * 常量池GC策略:只要常量池中的常量没有被任何地方引用,就可以被回收 diff --git a/src/main/java/com/JVM/stack/StackGCTest.java b/src/main/java/com/JVM/stack/StackGCTest.java index 580eb2e..98efc49 100644 --- a/src/main/java/com/JVM/stack/StackGCTest.java +++ b/src/main/java/com/JVM/stack/StackGCTest.java @@ -1,4 +1,4 @@ -package main.java.com.JVM.stack; +package com.ufclub.ljs.autoInvest.model.AutoInvestSettingcom.JVM.stack; /** * @author chenssy diff --git a/src/main/java/com/NIO/netty/Http/fileServer/HttpFileServer.java b/src/main/java/com/NIO/netty/Http/fileServer/HttpFileServer.java new file mode 100644 index 0000000..435a6e8 --- /dev/null +++ b/src/main/java/com/NIO/netty/Http/fileServer/HttpFileServer.java @@ -0,0 +1,50 @@ +package com.NIO.netty.Http.fileServer; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelInitializer; +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.http.HttpObjectAggregator; +import io.netty.handler.codec.http.HttpRequestDecoder; +import io.netty.handler.codec.http.HttpResponseEncoder; +import io.netty.handler.stream.ChunkedWriteHandler; + +public class HttpFileServer { + private static final String DEFAULT_URL = "/src/main/java/come/NIO/netty"; + + public void run(int port, final String url) throws Exception { + EventLoopGroup bossGroup = new NioEventLoopGroup(); + EventLoopGroup workerGroup = new NioEventLoopGroup(); + + try{ + ServerBootstrap sb = new ServerBootstrap(); + sb.group(bossGroup,workerGroup) + .channel(NioServerSocketChannel.class) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel socketChannel) throws Exception { + socketChannel.pipeline().addLast("http-decoder",new HttpRequestDecoder()); + socketChannel.pipeline().addLast("http-aggregator",new HttpObjectAggregator(65536)); + socketChannel.pipeline().addLast("http-encoder",new HttpResponseEncoder()); + socketChannel.pipeline().addLast("http-chunked",new ChunkedWriteHandler()); + socketChannel.pipeline().addLast("fileServerHandler",new HttpFileServerHandler(url)); + } + }); + + ChannelFuture future = sb.bind("127.0.0.1",port); + System.out.println("HTTP 文件目录服务器启动,网址是:http://127.0.0.1"); + + future.channel().closeFuture().sync(); + }finally { + bossGroup.shutdownGracefully(); + workerGroup.shutdownGracefully(); + } + } + + public static void main(String[] args) throws Exception { + new HttpFileServer().run(8999,"127.0.0.1"); + } +} diff --git a/src/main/java/com/NIO/netty/Http/fileServer/HttpFileServerHandler.java b/src/main/java/com/NIO/netty/Http/fileServer/HttpFileServerHandler.java new file mode 100644 index 0000000..23dde24 --- /dev/null +++ b/src/main/java/com/NIO/netty/Http/fileServer/HttpFileServerHandler.java @@ -0,0 +1,16 @@ +package com.NIO.netty.Http.fileServer; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.handler.codec.http.FullHttpRequest; + +public class HttpFileServerHandler extends SimpleChannelInboundHandler{ + public HttpFileServerHandler(String url) { + + } + + @Override + protected void messageReceived(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception { + + } +} diff --git a/src/main/java/com/NIO/netty/base/TimeClient.java b/src/main/java/com/NIO/netty/base/TimeClient.java new file mode 100644 index 0000000..e3519a0 --- /dev/null +++ b/src/main/java/com/NIO/netty/base/TimeClient.java @@ -0,0 +1,44 @@ +package com.NIO.netty.base; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.*; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; + +public class TimeClient { + + public void connect(int port, String host) { + // 配置客户端线程组 + EventLoopGroup group = new NioEventLoopGroup(); + + Bootstrap b = new Bootstrap(); + + try { + b.group(group).channel(NioSocketChannel.class) + .option(ChannelOption.TCP_NODELAY, true) + .handler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel socketChannel) throws Exception { + socketChannel.pipeline().addLast(new TimeClientHandler()); + } + }); + + // 发起异步连接操作 + ChannelFuture future = b.connect(host, port); + + // 等待客户端链路关闭 + + + future.channel().closeFuture().sync(); + } catch (InterruptedException e) { + + } finally { + group.shutdownGracefully(); + } + } + + public static void main(String[] args) { + new TimeClient().connect(8899,"127.0.0.1"); + } +} diff --git a/src/main/java/com/NIO/netty/base/TimeClientHandler.java b/src/main/java/com/NIO/netty/base/TimeClientHandler.java new file mode 100644 index 0000000..5fc2c53 --- /dev/null +++ b/src/main/java/com/NIO/netty/base/TimeClientHandler.java @@ -0,0 +1,45 @@ +package com.NIO.netty.base; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerAdapter; +import io.netty.channel.ChannelHandlerContext; + +public class TimeClientHandler extends ChannelHandlerAdapter{ + + private final 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); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + 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 exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + + System.out.println("cause by :" + cause.getMessage()); + + ctx.close(); + } +} diff --git a/src/main/java/com/NIO/netty/base/TimeServer.java b/src/main/java/com/NIO/netty/base/TimeServer.java new file mode 100644 index 0000000..428a541 --- /dev/null +++ b/src/main/java/com/NIO/netty/base/TimeServer.java @@ -0,0 +1,52 @@ +package com.NIO.netty.base; + +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; + +public class TimeServer { + + public void bind(int port){ + // 配置服务端的NIO线程组 + EventLoopGroup bossGroup = new NioEventLoopGroup(); // 用于服务端接受客户端的连接 + EventLoopGroup workerGroup = new NioEventLoopGroup(); // 用于进行SocketChannel的网络读写 + + try { + // ServerBootstrap 用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度 + ServerBootstrap b = new ServerBootstrap(); + b.group(bossGroup, workerGroup) + .channel(NioServerSocketChannel.class) + .option(ChannelOption.SO_BACKLOG, 1024) + .childHandler(new ChildChannelHanlder()); + + // 绑定端口,同步等待成功 + ChannelFuture future = b.bind(port).sync(); + // 等待服务端监听端口关闭 + future.channel().closeFuture().sync(); + + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + // 优雅地关闭 + bossGroup.shutdownGracefully(); + workerGroup.shutdownGracefully(); + } + } + + private class ChildChannelHanlder extends ChannelInitializer{ + + @Override + protected void initChannel(SocketChannel socketChannel) throws Exception { + socketChannel.pipeline().addLast(new TimerServerHandler()); + } + } + + public static void main(String[] args){ + new TimeServer().bind(8899); + } +} diff --git a/src/main/java/com/NIO/netty/base/TimerServerHandler.java b/src/main/java/com/NIO/netty/base/TimerServerHandler.java new file mode 100644 index 0000000..5ee15b9 --- /dev/null +++ b/src/main/java/com/NIO/netty/base/TimerServerHandler.java @@ -0,0 +1,39 @@ +package com.NIO.netty.base; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerAdapter; +import io.netty.channel.ChannelHandlerContext; + +import java.util.Date; + + +public class TimerServerHandler extends ChannelHandlerAdapter{ + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + 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 currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; + + ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes()); + + ctx.write(resp); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + ctx.close(); + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + ctx.flush(); + } +} diff --git a/src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoClient.java b/src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoClient.java new file mode 100644 index 0000000..0256bee --- /dev/null +++ b/src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoClient.java @@ -0,0 +1,50 @@ +package com.NIO.netty.frameDecoder.DelimiterBasedFrameDecoder; + +import io.netty.bootstrap.Bootstrap; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +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.DelimiterBasedFrameDecoder; +import io.netty.handler.codec.string.StringDecoder; + +public class EchoClient { + public void connect(int port,String host) throws Exception { + EventLoopGroup group = new NioEventLoopGroup(); + + try { + Bootstrap sb = new Bootstrap(); + sb.group(group).channel(NioSocketChannel.class) + .option(ChannelOption.TCP_NODELAY, true) + .handler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel socketChannel) throws Exception { + ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes()); + + socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter)); + + socketChannel.pipeline().addLast(new StringDecoder()); + + socketChannel.pipeline().addLast(new EchoClientHandler()); + } + }); + + ChannelFuture f = sb.connect(host,port).sync(); + + f.channel().closeFuture().sync(); + } finally { + group.shutdownGracefully(); + } + } + + public static void main(String[] args) throws Exception { + new EchoClient().connect(8999,"127.0.0.1"); + } + + +} diff --git a/src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoClientHandler.java b/src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoClientHandler.java new file mode 100644 index 0000000..bcd3434 --- /dev/null +++ b/src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoClientHandler.java @@ -0,0 +1,35 @@ +package com.NIO.netty.frameDecoder.DelimiterBasedFrameDecoder; + +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerAdapter; +import io.netty.channel.ChannelHandlerContext; + +public class EchoClientHandler extends ChannelHandlerAdapter{ + private int counter; + + // 末尾增加$_ + static final String ECHO_REQ = "Hi,chenssy,welcome to netty.$_"; + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + for(int i = 0 ; i < 10 ; i++){ + ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes())); + } + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + System.out.println("This is " + (++counter) + " times receive server:[" + msg + "]"); + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + ctx.flush(); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + cause.printStackTrace(); + ctx.close(); + } +} diff --git a/src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoServer.java b/src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoServer.java new file mode 100644 index 0000000..dab9ff6 --- /dev/null +++ b/src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoServer.java @@ -0,0 +1,58 @@ +package com.NIO.netty.frameDecoder.DelimiterBasedFrameDecoder; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.*; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.codec.DelimiterBasedFrameDecoder; +import io.netty.handler.codec.string.StringDecoder; + +/** + * DelimiterBasedFrameDecoder 服务端 + * + * @author chenssy + * @date 2017-05-08 + * @since v1.0.0 + */ +public class EchoServer { + + public void bind(int port) throws Exception { + // 配置线程组 + EventLoopGroup boosGroup = new NioEventLoopGroup(); + EventLoopGroup workerGroup = new NioEventLoopGroup(); + + try { + ServerBootstrap sb = new ServerBootstrap(); + sb.group(boosGroup, workerGroup) + .channel(NioServerSocketChannel.class) + .option(ChannelOption.SO_BACKLOG, 100) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel channel) throws Exception { + ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes()); + channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter)); + + channel.pipeline().addLast(new StringDecoder()); + channel.pipeline().addLast(new EchoServerHandler()); + } + }); + + //绑定端口 + ChannelFuture f = sb.bind(port).sync(); + + //等待服务端监听端口关闭 + f.channel().closeFuture().sync(); + } finally { + boosGroup.shutdownGracefully(); + workerGroup.shutdownGracefully(); + } + } + + public static void main(String[] args) throws Exception { + new EchoServer().bind(8999); + } + +} diff --git a/src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoServerHandler.java b/src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoServerHandler.java new file mode 100644 index 0000000..4bfca85 --- /dev/null +++ b/src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoServerHandler.java @@ -0,0 +1,32 @@ +package com.NIO.netty.frameDecoder.DelimiterBasedFrameDecoder; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerAdapter; +import io.netty.channel.ChannelHandlerContext; + +public class EchoServerHandler extends ChannelHandlerAdapter{ + + private int counter = 0; + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + String body = (String) msg; + + System.out.println("This is " + (++counter) + " times reveive client:[" + body + "]"); + + if(counter % 3 == 0){ + body += "$_"; + } + + ByteBuf buf = Unpooled.copiedBuffer(body.getBytes()); + + ctx.writeAndFlush(buf); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + cause.printStackTrace(); + ctx.close(); + } +} diff --git a/src/main/java/com/NIO/netty/frameDecoder/FixedLengthFrameDecoder/EchoServer.java b/src/main/java/com/NIO/netty/frameDecoder/FixedLengthFrameDecoder/EchoServer.java new file mode 100644 index 0000000..d566b4e --- /dev/null +++ b/src/main/java/com/NIO/netty/frameDecoder/FixedLengthFrameDecoder/EchoServer.java @@ -0,0 +1,61 @@ +package com.NIO.netty.frameDecoder.FixedLengthFrameDecoder; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +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.DelimiterBasedFrameDecoder; +import io.netty.handler.codec.FixedLengthFrameDecoder; +import io.netty.handler.codec.string.StringDecoder; + +/** + * DelimiterBasedFrameDecoder 服务端 + * + * @author chenssy + * @date 2017年05月08日 + * @since v1.0.0 + */ +public class EchoServer { + + public void bind(int port) throws Exception { + // 配置线程组 + EventLoopGroup boosGroup = new NioEventLoopGroup(); + EventLoopGroup workerGroup = new NioEventLoopGroup(); + + try { + ServerBootstrap sb = new ServerBootstrap(); + sb.group(boosGroup, workerGroup) + .channel(NioServerSocketChannel.class) + .option(ChannelOption.SO_BACKLOG, 100) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel channel) throws Exception { + channel.pipeline().addLast(new FixedLengthFrameDecoder(20)); + + channel.pipeline().addLast(new StringDecoder()); + channel.pipeline().addLast(new EchoServerHandler()); + } + }); + + //绑定端口 + ChannelFuture f = sb.bind(port).sync(); + + //等待服务端监听端口关闭 + f.channel().closeFuture().sync(); + } finally { + boosGroup.shutdownGracefully(); + workerGroup.shutdownGracefully(); + } + } + + public static void main(String[] args) throws Exception { + new EchoServer().bind(8999); + } + +} diff --git a/src/main/java/com/NIO/netty/frameDecoder/FixedLengthFrameDecoder/EchoServerHandler.java b/src/main/java/com/NIO/netty/frameDecoder/FixedLengthFrameDecoder/EchoServerHandler.java new file mode 100644 index 0000000..f56f605 --- /dev/null +++ b/src/main/java/com/NIO/netty/frameDecoder/FixedLengthFrameDecoder/EchoServerHandler.java @@ -0,0 +1,26 @@ +package com.NIO.netty.frameDecoder.FixedLengthFrameDecoder; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerAdapter; +import io.netty.channel.ChannelHandlerContext; + +public class EchoServerHandler extends ChannelHandlerAdapter{ + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + String body = (String) msg; + + System.out.println("Receive client : [" + body + "]"); + + ByteBuf buf = Unpooled.copiedBuffer(body.getBytes()); + + ctx.writeAndFlush(buf); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + cause.printStackTrace(); + ctx.close(); + } +} diff --git a/src/main/java/com/NIO/netty/tcpIP/NotStickers/TimeClient.java b/src/main/java/com/NIO/netty/tcpIP/NotStickers/TimeClient.java new file mode 100644 index 0000000..867e2d5 --- /dev/null +++ b/src/main/java/com/NIO/netty/tcpIP/NotStickers/TimeClient.java @@ -0,0 +1,46 @@ +package com.NIO.netty.tcpIP.NotStickers; + +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; + +public class TimeClient { + + public void connect(int port, String host) { + // 配置客户端线程组 + EventLoopGroup group = new NioEventLoopGroup(); + + Bootstrap b = new Bootstrap(); + + try { + b.group(group).channel(NioSocketChannel.class) + .option(ChannelOption.TCP_NODELAY, true) + .handler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel socketChannel) throws Exception { + socketChannel.pipeline().addLast(new TimeClientHandler()); + } + }); + + // 发起异步连接操作 + ChannelFuture future = b.connect(host, port); + + // 等待客户端链路关闭 + + future.channel().closeFuture().sync(); + } catch (InterruptedException e) { + + } finally { + group.shutdownGracefully(); + } + } + + public static void main(String[] args) { + new TimeClient().connect(8899,"127.0.0.1"); + } +} diff --git a/src/main/java/com/NIO/netty/tcpIP/NotStickers/TimeClientHandler.java b/src/main/java/com/NIO/netty/tcpIP/NotStickers/TimeClientHandler.java new file mode 100644 index 0000000..0e5fdcf --- /dev/null +++ b/src/main/java/com/NIO/netty/tcpIP/NotStickers/TimeClientHandler.java @@ -0,0 +1,52 @@ +package com.NIO.netty.tcpIP.NotStickers; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerAdapter; +import io.netty.channel.ChannelHandlerContext; + +public class TimeClientHandler extends ChannelHandlerAdapter{ + + private int counter; + + private byte[] req; + + + public TimeClientHandler(){ + req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes(); + } + + + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + ByteBuf message = null; + + for (int i = 0 ; i < 100 ; i++){ + message = Unpooled.buffer(req.length); + message.writeBytes(req); + + ctx.writeAndFlush(message); + } + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + 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 + "; the conters is :" + (++counter)); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + + System.out.println("cause by :" + cause.getMessage()); + + ctx.close(); + } +} diff --git a/src/main/java/com/NIO/netty/tcpIP/NotStickers/TimeServer.java b/src/main/java/com/NIO/netty/tcpIP/NotStickers/TimeServer.java new file mode 100644 index 0000000..46b12f0 --- /dev/null +++ b/src/main/java/com/NIO/netty/tcpIP/NotStickers/TimeServer.java @@ -0,0 +1,52 @@ +package com.NIO.netty.tcpIP.NotStickers; + +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; + +public class TimeServer { + + public void bind(int port){ + // 配置服务端的NIO线程组 + EventLoopGroup bossGroup = new NioEventLoopGroup(); // 用于服务端接受客户端的连接 + EventLoopGroup workerGroup = new NioEventLoopGroup(); // 用于进行SocketChannel的网络读写 + + try { + // ServerBootstrap 用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度 + ServerBootstrap b = new ServerBootstrap(); + b.group(bossGroup, workerGroup) + .channel(NioServerSocketChannel.class) + .option(ChannelOption.SO_BACKLOG, 1024) + .childHandler(new ChildChannelHanlder()); + + // 绑定端口,同步等待成功 + ChannelFuture future = b.bind(port).sync(); + // 等待服务端监听端口关闭 + future.channel().closeFuture().sync(); + + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + // 优雅地关闭 + bossGroup.shutdownGracefully(); + workerGroup.shutdownGracefully(); + } + } + + private class ChildChannelHanlder extends ChannelInitializer{ + + @Override + protected void initChannel(SocketChannel socketChannel) throws Exception { + socketChannel.pipeline().addLast(new TimerServerHandler()); + } + } + + public static void main(String[] args){ + new TimeServer().bind(8899); + } +} diff --git a/src/main/java/com/NIO/netty/tcpIP/NotStickers/TimerServerHandler.java b/src/main/java/com/NIO/netty/tcpIP/NotStickers/TimerServerHandler.java new file mode 100644 index 0000000..a3460cc --- /dev/null +++ b/src/main/java/com/NIO/netty/tcpIP/NotStickers/TimerServerHandler.java @@ -0,0 +1,45 @@ +package com.NIO.netty.tcpIP.NotStickers; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerAdapter; +import io.netty.channel.ChannelHandlerContext; + +import java.util.Date; + +/** + * 未考虑粘包拆包 + * + * @author chenssy + * @date 2017年05月05日 + * @since v1.0.0 + */ +public class TimerServerHandler extends ChannelHandlerAdapter{ + + private int counter; + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + ByteBuf buf = (ByteBuf) msg; + + byte[] req = new byte[buf.readableBytes()]; + buf.readBytes(req); + + String body = new String(req,"UTF-8").substring(0,req.length - System.getProperty("line.separator").length()); + + System.out.println("The time server receive order:" + body + "; the counter is " + (++counter)); + + String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; + + currentTime = currentTime + System.getProperty("line.separator"); + + ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes()); + + ctx.writeAndFlush(resp); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + ctx.close(); + } +} diff --git a/src/main/java/com/NIO/netty/tcpIP/stickers/TimeClient.java b/src/main/java/com/NIO/netty/tcpIP/stickers/TimeClient.java new file mode 100644 index 0000000..9c841a0 --- /dev/null +++ b/src/main/java/com/NIO/netty/tcpIP/stickers/TimeClient.java @@ -0,0 +1,50 @@ +package com.NIO.netty.tcpIP.stickers; + +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; +import io.netty.handler.codec.LineBasedFrameDecoder; +import io.netty.handler.codec.string.StringDecoder; + +public class TimeClient { + + public void connect(int port, String host) { + // 配置客户端线程组 + EventLoopGroup group = new NioEventLoopGroup(); + + Bootstrap b = new Bootstrap(); + + try { + b.group(group).channel(NioSocketChannel.class) + .option(ChannelOption.TCP_NODELAY, true) + .handler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel socketChannel) throws Exception { + socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024)); + socketChannel.pipeline().addLast(new StringDecoder()); + socketChannel.pipeline().addLast(new TimeClientHandler()); + } + }); + + // 发起异步连接操作 + ChannelFuture future = b.connect(host, port); + + // 等待客户端链路关闭 + + future.channel().closeFuture().sync(); + } catch (InterruptedException e) { + + } finally { + group.shutdownGracefully(); + } + } + + public static void main(String[] args) { + new TimeClient().connect(8899,"127.0.0.1"); + } +} diff --git a/src/main/java/com/NIO/netty/tcpIP/stickers/TimeClientHandler.java b/src/main/java/com/NIO/netty/tcpIP/stickers/TimeClientHandler.java new file mode 100644 index 0000000..32cf920 --- /dev/null +++ b/src/main/java/com/NIO/netty/tcpIP/stickers/TimeClientHandler.java @@ -0,0 +1,49 @@ +package com.NIO.netty.tcpIP.stickers; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerAdapter; +import io.netty.channel.ChannelHandlerContext; + +public class TimeClientHandler extends ChannelHandlerAdapter{ + + private int counter; + + private byte[] req; + + + public TimeClientHandler(){ + req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes(); + } + + + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + ByteBuf message = null; + + for (int i = 0 ; i < 100 ; i++){ + message = Unpooled.buffer(req.length); + message.writeBytes(req); + + ctx.writeAndFlush(message); + } + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + + + String body = (String) msg; + + System.out.println("Now is :" + body + "; the conters is :" + (++counter)); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + + System.out.println("cause by :" + cause.getMessage()); + + ctx.close(); + } +} diff --git a/src/main/java/com/NIO/netty/tcpIP/stickers/TimeServer.java b/src/main/java/com/NIO/netty/tcpIP/stickers/TimeServer.java new file mode 100644 index 0000000..40fe4d1 --- /dev/null +++ b/src/main/java/com/NIO/netty/tcpIP/stickers/TimeServer.java @@ -0,0 +1,61 @@ +package com.NIO.netty.tcpIP.stickers; + +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.LineBasedFrameDecoder; +import io.netty.handler.codec.string.StringDecoder; + + +public class TimeServer { + + public void bind(int port){ + // 配置服务端的NIO线程组 + EventLoopGroup bossGroup = new NioEventLoopGroup(); // 用于服务端接受客户端的连接 + EventLoopGroup workerGroup = new NioEventLoopGroup(); // 用于进行SocketChannel的网络读写 + + try { + // ServerBootstrap 用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度 + ServerBootstrap b = new ServerBootstrap(); + b.group(bossGroup, workerGroup) + .channel(NioServerSocketChannel.class) + .option(ChannelOption.SO_BACKLOG, 1024) + .childHandler(new ChildChannelHanlder()); + + // 绑定端口,同步等待成功 + ChannelFuture future = b.bind(port).sync(); + // 等待服务端监听端口关闭 + future.channel().closeFuture().sync(); + + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + // 优雅地关闭 + bossGroup.shutdownGracefully(); + workerGroup.shutdownGracefully(); + } + } + + private class ChildChannelHanlder extends ChannelInitializer{ + + @Override + protected void initChannel(SocketChannel socketChannel) throws Exception { + + // 解码器 + socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024)); + socketChannel.pipeline().addLast(new StringDecoder()); + + // 服务处理 + socketChannel.pipeline().addLast(new TimerServerHandler()); + } + } + + public static void main(String[] args){ + new TimeServer().bind(8899); + } +} diff --git a/src/main/java/com/NIO/netty/tcpIP/stickers/TimerServerHandler.java b/src/main/java/com/NIO/netty/tcpIP/stickers/TimerServerHandler.java new file mode 100644 index 0000000..d12f329 --- /dev/null +++ b/src/main/java/com/NIO/netty/tcpIP/stickers/TimerServerHandler.java @@ -0,0 +1,40 @@ +package com.NIO.netty.tcpIP.stickers; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerAdapter; +import io.netty.channel.ChannelHandlerContext; + +import java.util.Date; + +/** + * 未考虑粘包拆包 + * + * @author chenssy + * @date 2017年05月05日 + * @since v1.0.0 + */ +public class TimerServerHandler extends ChannelHandlerAdapter{ + + private int counter; + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + String body = (String) msg; + + System.out.println("The time server receive order:" + body + "; the counter is :" + (++counter)); + + String currentTime = " QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; + + currentTime = currentTime + System.getProperty("line.separator"); + + ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes()); + + ctx.writeAndFlush(resp); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + ctx.close(); + } +} diff --git a/src/main/java/com/NIO/nio/_1/MultiplexerTimerServer.java b/src/main/java/com/NIO/nio/_1/MultiplexerTimerServer.java new file mode 100644 index 0000000..d5625aa --- /dev/null +++ b/src/main/java/com/NIO/nio/_1/MultiplexerTimerServer.java @@ -0,0 +1,162 @@ +package com.NIO.nio._1; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.util.Date; +import java.util.Iterator; +import java.util.Set; + +/** + * 服务器端 + * + * @author chenssy + * @date 2017年04月20日 + * @since v1.0.0 + */ +public class MultiplexerTimerServer implements Runnable{ + + // 多路复用器 + private Selector selector; + + // 通道 + private ServerSocketChannel serverSocketChannel; + + private volatile boolean stop; + + MultiplexerTimerServer(int port){ + try { + // 打开通道channel,监听客户端连接 + selector = Selector.open(); + + serverSocketChannel = ServerSocketChannel.open(); + //监听端口 + serverSocketChannel.socket().bind(new InetSocketAddress(port),1024); + // 设置为非阻塞 + serverSocketChannel.configureBlocking(false); + + //将通道channel注册到多路复用器selector上面 + serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); + + System.out.println("The time server is start in port:" + port); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void stop(){ + this.stop = true; + } + + @Override + public void run() { + while (!stop){ + try { + selector.select(1000); + + Set selectionKeys = selector.selectedKeys(); + Iterator it = selectionKeys.iterator(); + + SelectionKey key = null; + + while (it.hasNext()){ + key = it.next(); + + it.remove(); + + try { + handleInput(key); + } catch (IOException e) { + if(key != null){ + key.cancel(); + if(key.channel() != null){ + key.channel().close(); + } + } + } + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + // 多路复用器关闭后,所有注册在上面的Channel等资源都会自动去注册并关闭,所以不需要重复释放资源 + if(selector != null){ + try { + selector.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + /** + * 处理链接请求 + * + * @author chenssy + * @date 2017年04月20日 + * @since v1.0.0 + */ + private void handleInput(SelectionKey key) throws IOException { + if(key.isValid()){ + // 处理新接入的请求 + if(key.isAcceptable()){ + ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); + + SocketChannel channel = ssc.accept(); + ssc.configureBlocking(false); + ssc.register(selector,SelectionKey.OP_READ); // 准备读 + } + + // 读取数据 + if(key.isReadable()){ + SocketChannel sc = (SocketChannel) key.channel(); + + ByteBuffer readBuffer = ByteBuffer.allocate(1024); + + int readBytes = sc.read(readBuffer); + + if(readBytes> 0){ + readBuffer.flip(); + + byte[] bytes = new byte[readBuffer.remaining()]; + + readBuffer.get(bytes); + String body = new String(bytes,"UTF-8"); + + System.out.println("The time server receive order:" + body); + String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; + + doWrite(sc,currentTime); + }else if(readBytes < 0){ + // 关闭终端 + key.cancel(); + sc.close(); + } + } + } + } + + /** + * 向客户端写入数据 + * + * @author chenssy + * @date 2017-04-20 + * @since v1.0.0 + */ + private void doWrite(SocketChannel channel, String response) throws IOException { + if(response != null && response.trim().length()> 0){ + byte[] bytes = response.getBytes(); + + ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length); + + writeBuffer.put(bytes); + writeBuffer.flip(); + channel.write(writeBuffer); + } + } +} diff --git a/src/main/java/com/NIO/nio/_1/TimeClientHandle.java b/src/main/java/com/NIO/nio/_1/TimeClientHandle.java new file mode 100644 index 0000000..c35f192 --- /dev/null +++ b/src/main/java/com/NIO/nio/_1/TimeClientHandle.java @@ -0,0 +1,82 @@ +package com.NIO.nio._1; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.SocketChannel; + +public class TimeClientHandle implements Runnable{ + private String host; + + private int port; + + private Selector selector; + + private SocketChannel socketChannel; + + private volatile boolean stop; + + public TimeClientHandle(String host,int port){ + this.host = host == null ? "127.0.0.1" : host; + this.port = port; + + try { + selector = Selector.open(); + socketChannel = SocketChannel.open(); + socketChannel.configureBlocking(false); + } catch (IOException e) { + e.printStackTrace(); + } + } + + + @Override + public void run() { + try { + doConnect(); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + /** + * 链接服务端 + * 如果链接成功,则注册到多路复用器上,发送请求消息,读应答 + * @author chenming + * @date 2017年04月20日 + * @since v1.0.0 + */ + private void doConnect() throws IOException { + if(socketChannel.connect(new InetSocketAddress(host,port))){ + socketChannel.register(selector, SelectionKey.OP_READ); + dowWrite(socketChannel); + }else{ + socketChannel.register(selector,SelectionKey.OP_CONNECT); + } + } + + /** + * 发送消息 + * + * @author chenming + * @date 2017年04月20日 + * @since v1.0.0 + */ + private void dowWrite(SocketChannel socketChannel) throws IOException { + byte[] req = "QUERY TIME ORDER".getBytes(); + + ByteBuffer writeBuffer = ByteBuffer.allocate(req.length); + + writeBuffer.put(req); + writeBuffer.flip(); + + socketChannel.write(writeBuffer); + + if(!writeBuffer.hasRemaining()){ + System.out.println("Send order 2 Server succeed."); + } + } +} diff --git a/src/main/java/com/redis/Test.java b/src/main/java/com/redis/Test.java new file mode 100644 index 0000000..2d39fe0 --- /dev/null +++ b/src/main/java/com/redis/Test.java @@ -0,0 +1,4 @@ +package com.redis; + +public class Test { +} diff --git a/src/test/Test.java b/src/test/Test.java new file mode 100644 index 0000000..cabd6d4 --- /dev/null +++ b/src/test/Test.java @@ -0,0 +1,12 @@ +package test; + +import java.util.concurrent.CopyOnWriteArrayList; + +public class Test { + + public static void main(String[] args) { + CopyOnWriteArrayList c = new CopyOnWriteArrayList(); + c.get(1); + } + +}

AltStyle によって変換されたページ (->オリジナル) /