netty是java的高性能socket框架,linux下基epoll,这里不对他多牛逼作分析,网上资料很多,这里针对一般socket的业务作个例子

几个基本概念:

  channel类似于socket句柄的抽象
  pipeline是每个socket里面的eventHandler的处理响应链

每个socket(channel)绑定一个pipeline,,每个pipeline绑定若干个handler,netty里面的handler,专门用来处理和业务有关的东西,handler有upHandler和downHandler,down用来处理发包,up用来处理收包,大概的示例图看这里

注意上面的123的顺序,很重要,在netty里面,处理顺序如图,对于up类的收包处理,最靠近收包层的顺序越靠前;对于down类的包处理,最靠近收包层的顺序越靠后

还有一些encoder和decoder,encoder用来在发包之前进行加密,decoder在收包以后进行解码,然后业务数据跳到事件处理流程。

下面具体上代码,版本是netty3.6

MessageClientHandler.java

 package com.netty.test.client;

 import java.util.logging.Level;
import java.util.logging.Logger; import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler; public class MessageClientHandler extends SimpleChannelUpstreamHandler { private static final Logger logger = Logger.getLogger(
MessageClientHandler.class.getName()); @Override
public void channelConnected(
ChannelHandlerContext ctx, ChannelStateEvent e) {
String message = "hello kafka0102";
e.getChannel().write(message);
} @Override
public void messageReceived(
ChannelHandlerContext ctx, MessageEvent e) {
// Send back the received message to the remote peer.
System.err.println("client messageReceived send message "+e.getMessage());
try {
Thread.sleep(1000*3);
} catch (Exception ex) {
ex.printStackTrace();
}
e.getChannel().write(e.getMessage());
} @Override
public void exceptionCaught(
ChannelHandlerContext ctx, ExceptionEvent e) {
// Close the connection when an exception is raised.
logger.log(
Level.WARNING,
"Unexpected exception from downstream.",
e.getCause());
e.getChannel().close();
}
}

MessageDecoder.java

 package com.netty.test.client;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder; public class MessageDecoder extends FrameDecoder { @Override
protected Object decode(
ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
if (buffer.readableBytes() < 4) {
return null;//(1)
}
int dataLength = buffer.getInt(buffer.readerIndex());
if (buffer.readableBytes() < dataLength + 4) {
return null;//(2)
} buffer.skipBytes(4);//(3)
byte[] decoded = new byte[dataLength];
buffer.readBytes(decoded);
String msg = new String(decoded);//(4)
return msg;
}
}

MessageEncoder.java

 package com.netty.test.client;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; public class MessageEncoder extends OneToOneEncoder { @Override
protected Object encode(
ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
if (!(msg instanceof String)) {
return msg;//(1)
} String res = (String)msg;
byte[] data = res.getBytes();
int dataLength = data.length;
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();//(2)
buf.writeInt(dataLength);
buf.writeBytes(data);
return buf;//(3)
}
}

用来测试的TestClientDownHandlerA.java

 package com.netty.test.client;

 import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.SimpleChannelDownstreamHandler; public class TestClientDownHandlerA extends SimpleChannelDownstreamHandler { public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e)
throws Exception {
System.err.println("test client Down handlerA "); super.handleDownstream(ctx, e);
}
}

用来测试的TestClientDownHandlerB.java

 package com.netty.test.client;

 import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.SimpleChannelDownstreamHandler; public class TestClientDownHandlerB extends SimpleChannelDownstreamHandler { public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e)
throws Exception {
System.err.println("test client Down handlerB "); super.handleDownstream(ctx, e);
}
}

MessageClientPipelineFactory.java

 package com.netty.test.client;

 import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels; import com.netty.test.client.MessageDecoder;
import com.netty.test.client.MessageEncoder; public class MessageClientPipelineFactory implements ChannelPipelineFactory { public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", new MessageDecoder());
pipeline.addLast("encoder", new MessageEncoder());
pipeline.addLast("handler", new MessageClientHandler()); pipeline.addFirst("testClientDownHandlerA", new TestClientDownHandlerA());
pipeline.addFirst("testClientDownHandlerB", new TestClientDownHandlerB()); return pipeline;
}
}

MessageClient.java

 package com.netty.test.client;

 import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; public class MessageClient { public static void main(String[] args) throws Exception {
// Parse options.
String host = "127.0.0.1";
int port = 8888;
// Configure the client.
ClientBootstrap bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
// Set up the event pipeline factory.
bootstrap.setPipelineFactory(new MessageClientPipelineFactory());
// Start the connection attempt.
ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
// Wait until the connection is closed or the connection attempt fails.
future.getChannel().getCloseFuture().awaitUninterruptibly();
// Shut down thread pools to exit.
bootstrap.releaseExternalResources();
}
}

客户端代码完成

以下为服务端测试代码

MessageDecoder和Messagencoder照抄,这个都是一样的

MessageServerHandler.java

 package com.netty.test.server;
import java.util.logging.Level;
import java.util.logging.Logger; import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler; public class MessageServerHandler extends SimpleChannelUpstreamHandler { private static final Logger logger = Logger.getLogger(
MessageServerHandler.class.getName()); @Override
public void messageReceived(
ChannelHandlerContext ctx, MessageEvent e) {
if (!(e.getMessage() instanceof String)) {
return;//(1)
}
String msg = (String) e.getMessage();
System.err.println("got msg:"+msg);
e.getChannel().write(msg);//(2)
} @Override
public void exceptionCaught(
ChannelHandlerContext ctx, ExceptionEvent e) {
logger.log(
Level.WARNING,
"Unexpected exception from downstream.",
e.getCause());
e.getChannel().close();
}
}

TestServerUpHandlerA.java

 package com.netty.test.server;

 import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler; public class TestServerUpHandlerA extends SimpleChannelUpstreamHandler { @Override
public void messageReceived(
ChannelHandlerContext ctx, MessageEvent e) {
// Send back the received message to the remote peer.
System.err.println("server test upHandlerA get message "+e.getMessage()); try {
super.messageReceived(ctx, e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} @Override
public void exceptionCaught(
ChannelHandlerContext ctx, ExceptionEvent e) { e.getChannel().close();
}
}

TestServerUpHandlerB.java

 package com.netty.test.server;

 import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler; public class TestServerUpHandlerB extends SimpleChannelUpstreamHandler { @Override
public void messageReceived(
ChannelHandlerContext ctx, MessageEvent e) {
// Send back the received message to the remote peer.
System.err.println("server test upHandlerB get message "+e.getMessage()); try {
super.messageReceived(ctx, e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} @Override
public void exceptionCaught(
ChannelHandlerContext ctx, ExceptionEvent e) { e.getChannel().close();
}
}

MessageServerPipelineFactory.java

 package com.netty.test.server;

 import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels; public class MessageServerPipelineFactory implements
ChannelPipelineFactory { public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", new MessageDecoder());
pipeline.addLast("encoder", new MessageEncoder());
pipeline.addLast("handler", new MessageServerHandler()); // pipeline.addFirst("testServerUpHandlerA", new TestServerUpHandlerA());
// pipeline.addFirst("testServerUpHandlerB", new TestServerUpHandlerB()); return pipeline;
}
}

MessageServer.java

 package com.netty.test.server;

 import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; public class MessageServer { public static void main(String[] args) throws Exception {
// Configure the server.
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool())); // Set up the default event pipeline.
bootstrap.setPipelineFactory(new MessageServerPipelineFactory()); // Bind and start to accept incoming connections.
bootstrap.bind(new InetSocketAddress(8888));
}
}

通过测试,可以发现handler的处理顺序,和图上面的是一致的;还有可以参考下encoder和decoder的写法,改改,直接用于项目。

netty初步的更多相关文章

  1. NIO原理剖析与Netty初步----浅谈高性能服务器开发(一)

    除特别注明外,本站所有文章均为原创,转载请注明地址 在博主不长的工作经历中,NIO用的并不多,由于使用原生的Java NIO编程的复杂性,大多数时候我们会选择Netty,mina等开源框架,但理解NI ...

  2. 架构师养成记--19.netty

    一.Netty初步 为什么选择Netty? 和NIO比较,要实现一个通信要简单得很多,性能很好.分布式消息中间件.storm.Dubble都是使用Netty作为底层通信. Netty5.0要求jdk1 ...

  3. netty学习记录1

    最近在学习netty,看的是<netty权威指南 第2版>. 然后看的同时也把书上面的代码一行行敲下来做练习,不过到第三章就出问题了. 按照书上讲的,sever/client端都需要继承C ...

  4. Socket网络通信编程(二)

    1.Netty初步 2.HelloWorld 3.Netty核心技术之(TCP拆包和粘包问题) 4.Netty核心技术之(编解码技术) 5.Netty的UDP实现 6.Netty的WebSocket实 ...

  5. 初步了解 Netty

    精通并发与 Netty (一)如何使用 精通并发与 Netty Netty 是一个异步的,事件驱动的网络通信框架,用于高性能的基于协议的客户端和服务端的开发. 异步指的是会立即返回,并不知道到底发送过 ...

  6. <Netty>(入门篇)TIP黏包/拆包问题原因及换行的初步解决之道

    熟悉TCP编程的读者可能都知道,无论是服务端还是客户端,当我们读取或者发送消息的时候,都需要考虑TCP底层的粘包/拆包机制.木章开始我们先简单介绍TCP粘包/拆包的基础知识,然后模拟一个没有考虑TCP ...

  7. java架构之路-(netty专题)初步认识BIO、NIO、AIO

    本次我们主要来说一下我们的IO阻塞模型,只是不多,但是一定要理解,对于后面理解netty很重要的 IO模型精讲  IO模型就是说用什么样的通道进行数据的发送和接收,Java共支持3种网络编程IO模式: ...

  8. Netty学习摘记 —— 初步认识Netty核心组件

    本文参考 我在博客内关于"Netty学习摘记"的系列文章主要是对<Netty in action>一书的学习摘记,文章中的代码也大多来自此书的github仓库,加上了一 ...

  9. Netty学习——Google Protobuf的初步了解

    学习参考的官网: https://developers.google.com/protocol-buffers/docs/javatutorial 简单指南详解:这个文档写的简直是太详细了. 本篇从下 ...

随机推荐

  1. Winform中用comboBox来选择显示Dataset中表格数据

    这是一次偷懒的尝试,因为每次都必须打开代码,调试才能看见数据,发现问题.也是借鉴了调试中查看dataset数据的模式,查看不同表格.经历一番研究,总算实现了想要的效果了,故作此一笔记.与人共享. 界面 ...

  2. Unity 3D连接MySQl数据库

    对数据库各种操作已经熟练,但是一遇到数据库问题还是头大,最近使用unity3d开发一款小型网络社区,遇到了各种问题分享一下以供大家参考: 以前使用的是SQL,第一次用MySQL,在网上随便下了一个,安 ...

  3. poj 1330 Nearest Common Ancestors(LCA 基于二分搜索+st&rmq的LCA)

    Nearest Common Ancestors Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 30147   Accept ...

  4. EhLib TitleButton SVisibleColumnsEh = '错误的列';

    unit EhLibConsts; interface resourcestring SClearSelectedCellsEh = '清除选择的单元?'; SInvalidTextFormatEh ...

  5. Spring学习笔记之各个包的作用

    (1) spring-core.jar 这个jar文件包含Spring框架基本的核心工具类,Spring其它组件要都要使用到这个包里的类,是其它组件的基本核心,当然你也可以在自己的应用系统中使用这些工 ...

  6. python笔记05:条件、循环和其它语句

    5.1 print和import的更多使用方式 5.1.1 使用逗号输出 print 'Age',42 print 1,2,3 如果要同时输出文本和变量值,又不希望使用字符串格式化的话,那么这个特性就 ...

  7. JavaScript事件简述

    事件简述 技术一般水平有限,有什么错的地方,望大家指正. 事件是我们平时经常使用,这次就来了解一下事件.首先我们要明确几个概念,JavaScript是单线程,浏览器是多线程的,并不是所有的事件处理函数 ...

  8. php and mysql 常用api函数

  9. Linux:挂载

    挂载

  10. centos 7安装tomcat

    1.下载安装包 http://tomcat.apache.org/download-80.cgi 2.安装tomcat 注:安装前需要安装jdk环境 #解压 [root@localhost soft] ...