nio使用之netty框架
来源:互联网 发布:linux sh 函数 编辑:程序博客网 时间:2024/05/19 00:16
1.官网上下载相应的jar包http://netty.io/downloads.html
当然,使用maven更方便,直接添加相应的依赖就行
2.创建工程,将下载好的包导入进去
这个是我的目录结构
服务器端:
1.创建HelloServer
package kang.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;public class HelloServer { /** * 服务端监听的端口地址 */ private static final int portNumber = 7878; public static void main(String[] args) throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.childHandler(new HelloServerInitializer()); // 服务器绑定端口监听 ChannelFuture f = b.bind(portNumber).sync(); // 监听服务器关闭监听 f.channel().closeFuture().sync(); // 可以简写为 /* b.bind(portNumber).sync().channel().closeFuture().sync(); */ } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }}
2.创建HelloServerInitializer
package kang.server;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.socket.SocketChannel;import io.netty.handler.codec.DelimiterBasedFrameDecoder;import io.netty.handler.codec.Delimiters;import io.netty.handler.codec.string.StringDecoder;import io.netty.handler.codec.string.StringEncoder;public class HelloServerInitializer extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();// 以("\n")为结尾分割的 解码器pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));// 字符串解码 和 编码pipeline.addLast("decoder", new StringDecoder());pipeline.addLast("encoder", new StringEncoder());// 自己的逻辑Handlerpipeline.addLast("handler", new HelloServerHandler());}}
3.创建HelloServerHandler
package kang.server;import java.net.InetAddress;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;public class HelloServerHandler extends SimpleChannelInboundHandler<String> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {// 收到消息直接打印输出System.out.println(ctx.channel().remoteAddress() + " Say : " + msg);// 返回客户端消息 - 我已经接收到了你的消息ctx.writeAndFlush("Received your message !\n");}/* * * 覆盖 channelActive 方法 在channel被启用的时候触发 (在建立连接的时候) * * channelActive 和 channelInActive 在后面的内容中讲述,这里先不做详细的描述 * */@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println("RamoteAddress : " + ctx.channel().remoteAddress() + " active !");ctx.writeAndFlush( "Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n");super.channelActive(ctx);}}
客户端:
1.创建HelloClient
package kang.client;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import io.netty.bootstrap.Bootstrap;import io.netty.channel.Channel;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioSocketChannel;public class HelloClient {public static String host = "127.0.0.1";public static int port = 7878;/** * @param args * @throws InterruptedException * @throws IOException */public static void main(String[] args) throws InterruptedException, IOException {EventLoopGroup group = new NioEventLoopGroup();try {Bootstrap b = new Bootstrap();b.group(group).channel(NioSocketChannel.class).handler(new HelloClientInitializer());// 连接服务端Channel ch = b.connect(host, port).sync().channel();// 控制台输入BufferedReader in = new BufferedReader(new InputStreamReader(System.in));for (;;) {String line = in.readLine();if (line == null||line.trim().equalsIgnoreCase("over")) {break;}/* * 向服务端发送在控制台输入的文本 并用"\r\n"结尾 * 之所以用\r\n结尾 是因为我们在handler中添加了 DelimiterBasedFrameDecoder 帧解码。 * 这个解码器是一个根据\n符号位分隔符的解码器。所以每条消息的最后必须加上\n否则无法识别和解码 * */ch.writeAndFlush(line + "\r\n");}} finally {// The connection is closed automatically on shutdown.group.shutdownGracefully();}}}
2.创建HelloClientInitializer
package kang.client;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.socket.SocketChannel;import io.netty.handler.codec.DelimiterBasedFrameDecoder;import io.netty.handler.codec.Delimiters;import io.netty.handler.codec.string.StringDecoder;import io.netty.handler.codec.string.StringEncoder;public class HelloClientInitializer extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();/* * 这个地方的 必须和服务端对应上。否则无法正常解码和编码 * * 解码和编码 我将会在下一张为大家详细的讲解。再次暂时不做详细的描述 * * */pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));pipeline.addLast("decoder", new StringDecoder());pipeline.addLast("encoder", new StringEncoder());// 客户端的逻辑pipeline.addLast("handler", new HelloClientHandler());}}
3.创建HelloClientHandler
package kang.client;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;public class HelloClientHandler extends SimpleChannelInboundHandler<String> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {System.out.println("Server say : " + msg);}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println("Client active ");super.channelActive(ctx);}@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {System.out.println("Client close ");super.channelInactive(ctx);}}
代码写好后,测试
客户端:
服务端:
阅读全文
0 0
- nio使用之netty框架
- 开源NIO框架Netty的使用
- Java NIO框架Netty简单使用
- NIO框架------Netty
- NIO流行框架 Netty
- java nio框架Netty
- 初学Java NIO框架Netty(一) 之 Hello
- Java NIO框架之Mina、Netty、Grizzly介绍与对比
- Java NIO框架之Mina、Netty、Grizzly介绍与对比
- netty框架学习1--使用NIO创建Server
- NIO Netty使用入门
- Java NIO框架Netty教程
- Java NIO框架Netty教程
- Java NIO通信框架: Netty
- Java NIO框架Netty教程
- Netty NIO框架初解
- netty框架的NIO类库
- nio实战之netty实现
- CPU调度算法
- 總結——關於2017 10 23測試的分析總結
- oracle hint(提示)大全
- Spring学习笔记(一)
- 17102101_CentOS7下利用systemd机制实现tomcat开机自启动
- nio使用之netty框架
- codeforces 411 div2-find amir
- 《c语言程序设计》例 2-8 2-9 2-10 2-11
- Gson 解析数组数组时
- springboot 快速集成的一些启动类模块
- 关于SimpleDateFormat安全的时间格式化线程安全问题
- Qt 学习 第6节 添加绘图控件Qwt
- ICCV2017: Unlabeled Samples Generated by GAN Improve the Person Re-Identification Baseline in Vitro
- openCV学习笔记(1)