以下两个例子基于netty-3.5.7.Final.jar用Junit进行测试
第一个例子:简单的发送字符串,接收字符串“Hello, World”
- class HelloWorldServerHandler extends SimpleChannelHandler {
- public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
- throws Exception {
- e.getChannel().write("Hello, World");
- }
- public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
- System.out.println("Unexpected exception from downstream."
- + e.getCause());
- e.getChannel().close();
- }
- }
- class HelloWorldClientHandler extends SimpleChannelHandler {
- public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
- String message = (String) e.getMessage();
- System.out.println(message);
- e.getChannel().close();
- }
- public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
- System.out.println("Unexpected exception from downstream."
- + e.getCause());
- e.getChannel().close();
- }
- }
- /**
- * Netty VS MinaNetty基于Pipeline处理,Mina基于Filter过滤
- * Netty的事件驱动模型具有更好的扩展性和易用性
- * Https,SSL,PB,RSTP,Text &Binary等协议支持
- * Netty中UDP传输有更好的支持官方测试Netty比Mina性能更好
- * @author Administrator
- *
- */
- public class TestCase {
- public void testServer() {
- //初始化channel的辅助类,为具体子类提供公共数据结构
- ServerBootstrap bootstrap = new ServerBootstrap(
- new NioServerSocketChannelFactory(
- Executors.newCachedThreadPool(),
- Executors.newCachedThreadPool()));
- bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
- public ChannelPipeline getPipeline() {
- ChannelPipeline pipeline = Channels.pipeline();
- pipeline.addLast("decoder", new StringDecoder());
- pipeline.addLast("encoder", new StringEncoder());
- pipeline.addLast("handler", new HelloWorldServerHandler());
- return pipeline;
- }
- });
- //创建服务器端channel的辅助类,接收connection请求
- bootstrap.bind(new InetSocketAddress(8080));
- }
- public void testClient() {
- //创建客户端channel的辅助类,发起connection请求
- ClientBootstrap bootstrap = new ClientBootstrap(
- new NioClientSocketChannelFactory(
- Executors.newCachedThreadPool(),
- Executors.newCachedThreadPool()));
- //It means one same HelloWorldClientHandler instance is going to handle multiple Channels and consequently the data will be corrupted.
- //基于上面这个描述,必须用到ChannelPipelineFactory每次创建一个pipeline
- bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
- public ChannelPipeline getPipeline() {
- ChannelPipeline pipeline = Channels.pipeline();
- pipeline.addLast("decoder", new StringDecoder());
- pipeline.addLast("encoder", new StringEncoder());
- pipeline.addLast("handler", new HelloWorldClientHandler());
- return pipeline;
- }
- });
- //创建无连接传输channel的辅助类(UDP),包括client和server
- ChannelFuture future = bootstrap.connect(new InetSocketAddress(
- "localhost", 8080));
- future.getChannel().getCloseFuture().awaitUninterruptibly();
- bootstrap.releaseExternalResources();
- }
- @Test
- public void testNetty(){
- testServer();
- testClient();
- }
- }
第二个例子,实际应用中会用到这个,发送POJO类Persons [name=周杰伦123, age=31, salary=10000.44]
- /**
- * 用POJO代替ChannelBuffer
- */
- class TimeServerHandler3 extends SimpleChannelHandler {
- @Override
- public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
- throws Exception {
- Persons person = new Persons("周杰伦123",31,10000.44);
- ChannelFuture future = e.getChannel().write(person);
- future.addListener(ChannelFutureListener.CLOSE);
- }
- }
- class TimeClientHandler3 extends SimpleChannelHandler{
- @Override
- public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
- throws Exception {
- Persons person = (Persons)e.getMessage();
- System.out.println(person);
- e.getChannel().close();
- }
- }
- /**
- * FrameDecoder and ReplayingDecoder allow you to return an object of any type.
- *
- */
- class TimeDecoder extends FrameDecoder {
- private final ChannelBuffer buffer = dynamicBuffer();
- @Override
- protected Object decode(ChannelHandlerContext ctx, Channel channel,
- ChannelBuffer channelBuffer) throws Exception {
- if(channelBuffer.readableBytes()<4) {
- return null;
- }
- if (channelBuffer.readable()) {
- // 读到,并写入buf
- channelBuffer.readBytes(buffer, channelBuffer.readableBytes());
- }
- int namelength = buffer.readInt();
- String name = new String(buffer.readBytes(namelength).array(),"GBK");
- int age = buffer.readInt();
- double salary = buffer.readDouble();
- Persons person = new Persons(name,age,salary);
- return person;
- }
- }
- class TimeEncoder extends SimpleChannelHandler {
- private final ChannelBuffer buffer = dynamicBuffer();
- @Override
- public void writeRequested(ChannelHandlerContext ctx, MessageEvent e)
- throws Exception {
- Persons person = (Persons)e.getMessage();
- buffer.writeInt(person.getName().getBytes("GBK").length);
- buffer.writeBytes(person.getName().getBytes("GBK"));
- buffer.writeInt(person.getAge());
- buffer.writeDouble(person.getSalary());
- Channels.write(ctx, e.getFuture(), buffer);
- }
- }
- class Persons{
- private String name;
- private int age;
- private double salary;
- public Persons(String name,int age,double salary){
- this.name = name;
- this.age = age;
- this.salary = salary;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public double getSalary() {
- return salary;
- }
- public void setSalary(double salary) {
- this.salary = salary;
- }
- @Override
- public String toString() {
- return "Persons [name=" + name + ", age=" + age + ", salary=" + salary
- + "]";
- }
- }
- public class TestCase5 {
- public void testServer() {
- ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
- ServerBootstrap bootstrap = new ServerBootstrap(factory);
- bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
- public ChannelPipeline getPipeline() throws Exception {
- return Channels.pipeline(new TimeEncoder(), new TimeServerHandler3());
- }
- });
- bootstrap.setOption("child.tcpNoDelay", true);
- bootstrap.setOption("child.keepAlive", true);
- bootstrap.bind(new InetSocketAddress("localhost",9999));
- }
- public void testClient(){
- //创建客户端channel的辅助类,发起connection请求
- ClientBootstrap bootstrap = new ClientBootstrap(
- new NioClientSocketChannelFactory(
- Executors.newCachedThreadPool(),
- Executors.newCachedThreadPool()));
- bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
- public ChannelPipeline getPipeline() {
- ChannelPipeline pipeline = Channels.pipeline();
- pipeline.addLast("decoder", new TimeDecoder());
- pipeline.addLast("encoder", new TimeEncoder());
- pipeline.addLast("handler", new TimeClientHandler3());
- return pipeline;
- }
- });
- //创建无连接传输channel的辅助类(UDP),包括client和server
- ChannelFuture future = bootstrap.connect(new InetSocketAddress(
- "localhost", 9999));
- future.getChannel().getCloseFuture().awaitUninterruptibly();
- bootstrap.releaseExternalResources();
- }
- @Test
- public void testNetty() {
- testServer();
- testClient();
- }
- }
这两段代码是学习的时候参考别人的代码,转于哪想不起来了,但是这两段代码让我了解了netty的通信流程。
相关推荐
Netty 框架学习 —— 第一个 Netty 应用(csdn)————程序
Netty 框架学习 —— 编解码器框架(csdn)————程序
Netty 框架学习 —— 预置的 ChannelHandler 和编解码器(csdn)————程序
《Netty最佳实践》——《Netty实战》补遗-Netty-Best-Practices
Netty基础,用于学习Netty,参考黑马程序员的netty教程
Netty在Android开发中的应用实战系列(二)——— Encoder | Decoder | Handler 的使用:https://azhon.blog.csdn.net/article/details/100831777 Netty在Android开发中的应用实战系列(三)——— 心跳处理 | 断线...
也就是说,Netty 是一个基于NIO的客户,服务器端编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户,服务端应用。Netty相当简化和流线化了网络应用的编程开发过程,例如,...
NettyDemo Netty使用实例,对象传递调用; LineBasedFrameDecoder + 消息中得换行符;解决TCP 粘包问题; Java序列化方案编解码对比;对象调用方案
Netty学习笔记_Springboot实现自定义协议.docx Netty学习笔记_Springboot实现自定义协议.docx Netty学习笔记_Springboot实现自定义协议.docx
netty-3.1官网学习手册,中文版
博客文章对应的源代码,只是简单的使用,属于入门级别
学习netty源码,为后续rocketmq等学习打下基础
Netty权威 第2版 带书签目录 RPC dubbo Netty权威 第2版 带书签目录 RPC dubbo Netty权威 第2版 带书签目录 RPC dubbo Netty权威 第2版 带书签目录 RPC dubbo Netty权威 第2版 带书签目录 RPC dubbo Netty权威 第2版...
SpringBoot_Netty实例,自己参考W3H而写,可以跑通,有编码器等,具有参考价值。注意是springboot的框架 也可以不用springboot.普通类写的
spring+netty+mybatis整合实例 实现一个简单的socket服务,启动服务后,客户端发送一条消息,服务端从数据库查询数据并返回给客户端。
所以想学好Socket通信不是件容易事,那么接下来就来学习一下新的技术Netty,为什么会选择Netty?因为它简单!使用Netty不必编写复杂的逻辑代码去实现通信,再也不需要去考虑性能问题,不需要考虑编码问题,半包读写...
Netty同步等待数据返回实例代码
netty学习资料(java源代码实例).zip
Netty 5.0.0.Alpha2 版本,包含:Jar包+源代码+API文档。 官网Netty 5.0版本已经废弃,所以发布出来,方便大家下载。 《Netty权威指南》一书使用的就是Netty 5.0
netty聊天室实例