Netty4 学习笔记之一:客户端与服务端通信 demo
前言
因为以前在项目中使用过Mina框架,感受到了该框架的强大之处。于是在业余时间也学习了一下Netty。因为Netty的主要版本是Netty3和Netty4(Netty5已经被取消了),所以我就直接学习Netty4。在本文中演示的就是Netty的一个简单demo。
开发准备
Netty4的官方网站是:http://netty.io/ 。
本文使用的是Netty4.1。
由于Netty4.1版本需要JDK1.7,在使用JDK1.6时,会有一些bug,所以推荐使用JDK1.7。
因为Netty和Mina都是Trustin Lee的作品,所以在很多方面都十分相似,他们线程模型也是基本一致,采用了Reactors in threads模型,即Main Reactor + Sub Reactors的模式。
所以在开发上,很多都可以相互借鉴。
服务端
首先完成Netty服务端相关开发,和Mina一样。
主要由两个部分组成: 配置服务端的基本信息以及实现业务逻辑处理。
如果需要,还有filter过滤器。
服务端代码
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;/***
* Title: NettyServer
* Description: Netty服务端
* Version:1.0.0
* @author Administrator
* @date 2017-8-31*/
public class NettyServer {private static final int port = 6789; //设置服务端端口private static EventLoopGroup group = new NioEventLoopGroup(); // 通过nio方式来接收连接和处理连接 private static ServerBootstrap b = new ServerBootstrap();/*** Netty创建全部都是实现自AbstractBootstrap。* 客户端的是Bootstrap,服务端的则是 ServerBootstrap。**/public static void main(String[] args) throws InterruptedException {try {b.group(group);b.channel(NioServerSocketChannel.class);b.childHandler(new NettyServerFilter()); //设置过滤器// 服务器绑定端口监听ChannelFuture f = b.bind(port).sync();System.out.println("服务端启动成功...");// 监听服务器关闭监听f.channel().closeFuture().sync();} finally {group.shutdownGracefully(); 关闭EventLoopGroup,释放掉所有资源包括创建的线程 }}
}
服务端业务逻辑
import java.net.InetAddress;
import java.util.Date;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;/***
* Title: HelloServerHandler
* Description: 服务端业务逻辑
* Version:1.0.0
* @author Administrator
* @date 2017-8-31*/
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {/** 收到消息时,返回信息*/@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String msg)throws Exception {// 收到消息直接打印输出System.out.println("服务端接受的消息 : " + msg);if("quit".equals(msg)){//服务端断开的条件ctx.close();}Date date=new Date();// 返回客户端消息ctx.writeAndFlush(date+"\n");}/** 建立连接时,返回消息*/@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println("连接的客户端地址:" + ctx.channel().remoteAddress());ctx.writeAndFlush("客户端"+ InetAddress.getLocalHost().getHostName() + "成功与服务端建立连接! \n");super.channelActive(ctx);}
}
服务端过滤器
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;/*** * Title: HelloServerInitializer* Description: Netty 服务端过滤器* Version:1.0.0 * @author Administrator* @date 2017-8-31*/
public class NettyServerFilter extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline ph = ch.pipeline();// 以("\n")为结尾分割的 解码器ph.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));// 解码和编码,应和客户端一致ph.addLast("decoder", new StringDecoder());ph.addLast("encoder", new StringEncoder());ph.addLast("handler", new NettyServerHandler());// 服务端业务逻辑}}
客户端
客户端的主要工作是
1,连接到服务端
2,向服务端发送数据数据
3,处理服务端返回的数据
4,关闭连接
而且客户端相关代码也和服务端类似。
客户端
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;import java.io.IOException;
/***
* Title: NettyClient
* Description: Netty客户端
* Version:1.0.0
* @author Administrator
* @date 2017-8-31*/
public class NettyClient {public static String host = "127.0.0.1"; //ip地址public static int port = 6789; //端口/// 通过nio方式来接收连接和处理连接 private static EventLoopGroup group = new NioEventLoopGroup(); private static Bootstrap b = new Bootstrap();private static Channel ch;/*** Netty创建全部都是实现自AbstractBootstrap。* 客户端的是Bootstrap,服务端的则是 ServerBootstrap。**/public static void main(String[] args) throws InterruptedException, IOException { System.out.println("客户端成功启动...");b.group(group);b.channel(NioSocketChannel.class);b.handler(new NettyClientFilter());// 连接服务端ch = b.connect(host, port).sync().channel();star();}public static void star() throws IOException{String str="Hello Netty";ch.writeAndFlush(str+ "\r\n");System.out.println("客户端发送数据:"+str);}}
客户端业务逻辑实现
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;/***
* Title: NettyClientHandler
* Description: 客户端业务逻辑实现
* Version:1.0.0
* @author Administrator
* @date 2017-8-31*/
public class NettyClientHandler extends SimpleChannelInboundHandler<String> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println("客户端接受的消息: " + msg);}//@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println("正在连接... ");super.channelActive(ctx);}@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {System.out.println("连接关闭! ");super.channelInactive(ctx);}
}
客户端过滤器
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;
/***
* Title: NettyClientFilter
* Description: Netty客户端 过滤器
* Version:1.0.0
* @author Administrator
* @date 2017-8-31*/
public class NettyClientFilter extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline ph = ch.pipeline();/** 解码和编码,应和服务端一致* */ph.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));ph.addLast("decoder", new StringDecoder());ph.addLast("encoder", new StringEncoder());ph.addLast("handler", new NettyClientHandler()); //客户端的逻辑}
}
效果实现图
服务端
客户端
demo教程到这里就结束了,如果有什么问题,欢迎提出!
该项目我放在github上了,有兴趣的可以看看!https://github.com/xuwujing/Netty
转载于:https://www.cnblogs.com/xuwujing/p/7536702.html
Netty4 学习笔记之一:客户端与服务端通信 demo相关推荐
- 浅议C#客户端和服务端通信的几种方法:Rest和GRPC和其他
本文来自:https://michaelscodingspot.com/rest-vs-grpc-for-asp-net/ 浅议C#客户端和服务端通信的几种方法:Rest和GRPC 在C#客户端和C# ...
- socket java 客户端_Java基于socket实现的客户端和服务端通信功能完整实例
本文实例讲述了Java基于socket实现的客户端和服务端通信功能.分享给大家供大家参考,具体如下: 以下代码参考马士兵的聊天项目,先运行ChatServer.java实现端口监听,然后再运行Chat ...
- 《Netty权威指南 第2版》学习笔记(1)---服务端与客户端开发入门
前言 Netty权威指南中以时间服务器为入门案例,演示了如何通过Netty完成了服务端与客户端之间的交互过程. 在开始使用Netty开发之前,先回顾一下使用NIO进行服务端开发的步骤. 创建Serve ...
- Java笔记-为客户端及服务端创建公私钥的密钥库
使用密钥库使得客户端与服务器之间进行安全的通信,通过下面的方式生成公钥私钥库: 1. 创建client及server的keystore. 2. 从keystore中导出certificate. 3. ...
- EJB3.0学习笔记---理解远程调用服务端和本地调用服务端的区别
项目目的:理解远程调用服务端和本地调用服务端的区别 1.异常: javax.ejb.EJBException: Local and Remote Interfaces cannot hav ...
- 【Go语言学习】——HTTP客户端和服务端
HTTP客户端和服务端 参考博客 HTTP客户端就是浏览器,而服务端就是后台服务器 HTTP协议规定了浏览器和网站服务器之间通信的规则,HTML通过标签符号为页面增添元素,CSS就是为了形成不同的颜色 ...
- Java--Socket客户端,服务端通信
1.客户端接受服务端的消息并打印: 客户端: import java.io.BufferedReader; import java.io.IOException; import java.io.Inp ...
- 客户端和服务端通信原理
客户端和服务端 客户端:可以向服务端发起请求的,并且接受返回的内容的进行处理 服务器端:能够接受客户端的请求,并且把相关资源信息返回给客户端的 web 服务站点 详细 url 地址解析 DNS 服务器 ...
- Java中Socket实现客户端和服务端通信(多线程实现全双工通信)
效果图 目录结构 服务端Server package server;import thread.SocketReader; import thread.SocketWrite;import java. ...
最新文章
- 通过 ANE(Adobe Native Extension) 启动Andriod服务 推送消息(二)
- InfluxDB学习之InfluxDB的基本操作
- 【51单片机快速入门指南】2.3:GPIO读取矩阵键盘 8个IO读16键
- android webapi 返回html 代码,ANDROID调用VS2013 ASP.NET WEBAPI 返回DATATABLE 注意
- 使用 Python 为女神挑选口红 ,成功把女神拿下,你学会了吗
- 考研总分多少能去辽师_辽宁师范大学在职研究生统考分数到达到多少呢统考通过就会被录取吗...
- mysql实战20 | 幻读是什么,幻读有什么问题?
- Fiddler笔记(4)浏览器抓包
- 回味Python2.7——笔记3
- 3.手动搭建Maven项目
- lnmp升级PHP环境
- cad2018安装教程_AUTO CAD2018安装教程+安装包
- 搜狗输入法 VS 拼音加加
- ios storyboard 传参 返回传参(segue)
- xp系统如何更改计算机用户名,xp用administrator_XP系统修改administrator的用户名_xpadministrator...
- R语言caret包preProcess()标准化出现错误: Matrices or data frames are required for preprocessing
- obj转stl_STL转STP的方法视频教程,OBJ格式转STP或者IGS开模具格式的过程,STL转STP软件介绍...
- 2016 威斯康星 计算机科学,威斯康星麦迪逊大学计算机科学本科申请条件及案例分析...
- 自己写USB Joystick驱动
- Computational Intelligence Assisted Design -- In Industrial Revolution 4.0 (计算智能在工业4.0的应用) --绪论