Java的网络操作一直比较复杂,虽然说在加入NIO之后简单了些,但还不是我这些菜鸟玩得起的,由于存在大量低层操作和协议处理,所以在使用上面还是很难。迄今为止,还没有用NIO写出稳定可靠的网络操作,也许这和具体的应用需求较少也有关系吧。
大概也有人和我对NIO有同样的想法,他们最NIO进行了一些封装,所以就有了MIna和现在的Netty。
Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序[官方定义],整体来看其包含了以下内容:
1.提供了丰富的协议编解码支持,
2.实现自有的buffer系统,减少复制所带来的消耗,
3.整套channel的实现,
4.基于事件的过程流转以及完整的网络事件响应与扩展,
5.丰富的example。
有了Netty之后,网络编程最起码会大大简化,并且我们也不需要为性能问题担心,Netty并发两三万还是没什么太大问题的。已经有人进行过实验了。
本文主要是列举Netty初步使用的一个最基本的例子,具体的说明在代码中都有了,所以也不再重复。
java的学习是从Hello word开始的,Netty也从这里开始吧。
这里的例子比较简单,后面会慢慢的对Netty的一些复杂应用、Netty的原理进行一些解析。
1、ClientThread.java
- package HelloWord;
- import static org.jboss.netty.channel.Channels.pipeline;
- 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.ChannelPipeline;
- import org.jboss.netty.channel.ChannelPipelineFactory;
- import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
- import org.jboss.netty.handler.codec.string.StringDecoder;
- import org.jboss.netty.handler.codec.string.StringEncoder;
- /**
- * 启动一个client线程,用来间歇性的发送消息
- * @author Ransom
- */
- public class ClientThread implements Runnable
- {
- private ChannelFuture future;
- public ChannelFuture getFuture()
- {
- return future;
- }
- public void setFuture(ChannelFuture future)
- {
- this.future = future;
- }
- @Override
- public void run()
- {
- /*
- * 实例化一个客户端Bootstrap实例,
- * NioClientSocketChannelFactory是Netty默认提供的。
- * 两个参数,一个是boss的线程池,一个是worker执行的线程池。
- * 两个线程池都使用了java.util.concurrent.Executors中的线程池来创建。
- */
- ClientBootstrap bootstrap = new ClientBootstrap(
- new NioClientSocketChannelFactory(
- Executors.newCachedThreadPool(),
- Executors.newCachedThreadPool()));
- /*
- * 设置piplineFactory,
- * 顾名思义,就是产生默认的pipline。
- * pipline的实例是DefaultChannelPipeline
- * 提供了链式的事件通讯机制
- */
- bootstrap.setPipelineFactory(new ChannelPipelineFactory(){
- /*
- * (non-Javadoc)
- * @see org.jboss.netty.channel.ChannelPipelineFactory#getPipeline()
- */
- @Override
- public ChannelPipeline getPipeline() throws Exception
- {
- /*
- * 在DefaultChannelPipeline的过滤器 链中实现了
- * encode 、decode、handler
- * 其中encode实现自ChannelDownstreamHandler接口
- * decode、Handler实现自ChannelUpstreamHandler接口
- * 也就说明了在client发送消息的时候,默认按照顺序会先调用decode
- * 在client接收到响应的时候,会按照顺序调用encode和Handler。
- * 后面会有文章专门将ChannelDownstreamHandler和ChannelUpstreamHandler的调用顺序。
- */
- ChannelPipeline pipleline = pipeline();
- pipleline.addLast("encode", new StringEncoder());
- pipleline.addLast("decode", new StringDecoder());
- pipleline.addLast("handler", new Handler());
- return pipleline;
- }
- });
- /*
- * 与127.0.0.1建立长连接。
- */
- future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 8080));
- }
- /**
- * 发送消息至server
- */
- public void sendMsg()
- {
- if(future==null) return;
- String s = "Hello Word!";
- future.getChannel().write(s);
- }
- }
package HelloWord; import static org.jboss.netty.channel.Channels.pipeline; 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.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; /** * 启动一个client线程,用来间歇性的发送消息 * @author Ransom */ public class ClientThread implements Runnable { private ChannelFuture future; public ChannelFuture getFuture() { return future; } public void setFuture(ChannelFuture future) { this.future = future; } @Override public void run() { /* * 实例化一个客户端Bootstrap实例, * NioClientSocketChannelFactory是Netty默认提供的。 * 两个参数,一个是boss的线程池,一个是worker执行的线程池。 * 两个线程池都使用了java.util.concurrent.Executors中的线程池来创建。 */ ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); /* * 设置piplineFactory, * 顾名思义,就是产生默认的pipline。 * pipline的实例是DefaultChannelPipeline * 提供了链式的事件通讯机制 */ bootstrap.setPipelineFactory(new ChannelPipelineFactory(){ /* * (non-Javadoc) * @see org.jboss.netty.channel.ChannelPipelineFactory#getPipeline() */ @Override public ChannelPipeline getPipeline() throws Exception { /* * 在DefaultChannelPipeline的过滤器 链中实现了 * encode 、decode、handler * 其中encode实现自ChannelDownstreamHandler接口 * decode、Handler实现自ChannelUpstreamHandler接口 * 也就说明了在client发送消息的时候,默认按照顺序会先调用decode * 在client接收到响应的时候,会按照顺序调用encode和Handler。 * 后面会有文章专门将ChannelDownstreamHandler和ChannelUpstreamHandler的调用顺序。 */ ChannelPipeline pipleline = pipeline(); pipleline.addLast("encode", new StringEncoder()); pipleline.addLast("decode", new StringDecoder()); pipleline.addLast("handler", new Handler()); return pipleline; } }); /* * 与127.0.0.1建立长连接。 */ future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 8080)); } /** * 发送消息至server */ public void sendMsg() { if(future==null) return; String s = "Hello Word!"; future.getChannel().write(s); } }
2、Handler.java
- package HelloWord;
- import org.jboss.netty.channel.ChannelHandlerContext;
- import org.jboss.netty.channel.ExceptionEvent;
- import org.jboss.netty.channel.MessageEvent;
- import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
- /**
- * client和server接收消息共用的handler
- * 由于两个都是继承自SimpleChannelUpstreamHandler,所以就写在一起了。
- * @author Ransom
- *
- */
- public class Handler extends SimpleChannelUpstreamHandler
- {
- public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
- throws Exception
- {
- System.out.println("recive message,message content:"+e.getMessage());
- }
- public void exceptionCaught(
- ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
- System.err.println("Client has a error,Error cause:"+e.getCause());
- e.getChannel().close();
- }
- }
package HelloWord; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * client和server接收消息共用的handler * 由于两个都是继承自SimpleChannelUpstreamHandler,所以就写在一起了。 * @author Ransom * */ public class Handler extends SimpleChannelUpstreamHandler { public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { System.out.println("recive message,message content:"+e.getMessage()); } public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { System.err.println("Client has a error,Error cause:"+e.getCause()); e.getChannel().close(); } }
3、Server.java
- package HelloWord;
- import static org.jboss.netty.channel.Channels.pipeline;
- import java.net.InetSocketAddress;
- import java.util.concurrent.Executors;
- import org.jboss.netty.bootstrap.ServerBootstrap;
- import org.jboss.netty.channel.ChannelPipeline;
- import org.jboss.netty.channel.ChannelPipelineFactory;
- import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
- import org.jboss.netty.handler.codec.string.StringDecoder;
- import org.jboss.netty.handler.codec.string.StringEncoder;
- /**
- * 在本地8080端口启动netty服务
- * @author Ransom
- *
- */
- public class Server
- {
- public static void main(String[] args)
- {
- /*
- * server的注释和client类似,在这里就不重复了
- * 但是需要注意的是server初始化的是ServerBootstrap的实例
- * client初始化的是ClientBootstrap,两个是不一样的。
- * 里面的channelfactory也是NioServerSocketChannelFactory。
- */
- ServerBootstrap bootstrap = new ServerBootstrap(
- new NioServerSocketChannelFactory(
- Executors.newCachedThreadPool(),
- Executors.newCachedThreadPool()));
- bootstrap.setPipelineFactory(new ChannelPipelineFactory()
- {
- @Override
- public ChannelPipeline getPipeline() throws Exception
- {
- ChannelPipeline pipleline = pipeline();
- pipleline.addLast("encode", new StringEncoder());
- pipleline.addLast("decode", new StringDecoder());
- pipleline.addLast("handler", new Handler());
- return pipleline;
- }
- });
- bootstrap.bind(new InetSocketAddress(8080));
- }
- }
package HelloWord; import static org.jboss.netty.channel.Channels.pipeline; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; /** * 在本地8080端口启动netty服务 * @author Ransom * */ public class Server { public static void main(String[] args) { /* * server的注释和client类似,在这里就不重复了 * 但是需要注意的是server初始化的是ServerBootstrap的实例 * client初始化的是ClientBootstrap,两个是不一样的。 * 里面的channelfactory也是NioServerSocketChannelFactory。 */ ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipleline = pipeline(); pipleline.addLast("encode", new StringEncoder()); pipleline.addLast("decode", new StringDecoder()); pipleline.addLast("handler", new Handler()); return pipleline; } }); bootstrap.bind(new InetSocketAddress(8080)); } }
4、HelloWordMain.java
- package HelloWord;
- /**
- * Netty 初步之hello word的client入口
- * @author Ransom
- *
- */
- public class HelloWordMain
- {
- public static void main(String[] args)
- {
- ClientThread r = new ClientThread();
- Thread t = new Thread(r);
- t.setName("client thread");
- t.start();
- while(true)
- {
- try
- {
- Thread.sleep(3000);
- } catch (InterruptedException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- r.sendMsg();
- }
- }
- }
相关推荐
netty4.x的hello world 范例,可以运行,直接导入工程,需要依赖包netty-all-4.0.25.final.jar,可以去MAVEN仓库下载或者百度下载。
Netty之helloworld示列,客户端,服务器示列代码,欢迎初学者学习。
Netty入门,HelloWorld Demo 以及实现了心跳机制的HeartBeat Demo
1.netty入门 -- netty-helloworld 2.netty的粘包 - netty-stick 3.netty支持的各协议,包含messagepack、protobuf以及私有协议 - netty-protocol 4.netty开发httpserver服务 - netty-httpserver 5.netty开发...
Netty在IDEA中搭建HelloWorld服务端并对Netty执行流程与重要组件进行介绍示例代码;Netty在IDEA中搭建HelloWorld服务端并对Netty执行流程与重要组件进行介绍示例代码
近百节视频详细讲解,需要的小伙伴自行百度网盘下载,链接见附件,永久有效...2. Hello World 3. 组件 4. 双向通信 三. Netty 进阶 1. 粘包与半包 2. 协议设计与解析 3. 聊天室案例 四. 优化与源码 1. 优化 2. 源码分析
Ktor is a framework for quickly creating web applications in Kotlin with minimal effort.... call.respondText("Hello, world!", ContentType.Text.Html) } } }.start(wait = true) } Runs embedded web serve
01、Mina服务端helloWorld入门.flv 02、Mina客户端helloWorld入门.flv 03、Mina整体体系结构分析.flv 04、Mina学习之长短连接.flv 05、Mina学习之MinaIOService接口.flv 06、Mina学习之MinaIOFilter接口.flv ...
netty android收发消息的hello World ,代码包含android客户端(studio)和服务端,简单实现收发消息交互
cassandra-netty-rest-simple 集成了Cassandra,Netty和JBoss RESTEasy的简单应用程序。 它提供了一个Hello World REST Web服务,可以通过。 调用服务时,它将Person的实例持久化到名为DEMO的Cassandra键空间中。
Test http://localhost:8082/resteasy/hello/world 教程 jax-rs规范用法: http://www.vogella.com/tutorials/REST/article.html resteasy 教程: http://code.freedomho.com/9541.html 名次解释 RESTEasy:RESTEasy...
NettyHttp服务器基于Netty框架的简单Http Server Netty Framework 版本 4.0.26.Final 已使用(稳定来自 maven repo) -request 在 10 秒内显示“Hello World”。 -request 重定向到 。 -request 显示有关连接、请求...
Java-netty.io HTTP Server / w netty.io 框架需要在netty框架( )上实现一个http服务器,功能如下: 根据对请求在 10 秒后给出“Hello World” 根据对请求,重定向到指定的 url 根据对请求统计信息: 请求总数唯一...
netty开发入门,包含hello world,Server与Client通讯。
《Netty 实战》 Netty In Action 中文版 代码清单已经更新到 Netty 4.1.11.final 内容提要 本书是为想要或者正在使用 Java 从事高性能网络编程的人而写的,循序渐进地介绍了 Netty 各个方面的内容。 本书共分为 4 ...
Ktor是用于创建微服务,Web应用程序等的异步框架... call.respondText( " Hello, world! " , ContentType . Text . Html ) } } }.start(wait = true ) } 在localhost:8080上运行嵌入式Web服务器 安装路由并用Hello
:OK_hand: :netty-helloworld b。 『基础-通讯协议篇』 :OK_hand: :netty-http :OK_hand: netty-springboot-protobuf :OK_hand: netty-mqtt C。 『中级-数据传输篇』 Netty碰上关系型数据库 :monkey: ...
Ktor是一个框架,用于以最小的努力在Kotlin中快速创建...){EmbeddedServer(Netty,8080){路由{get(“ /”){call.respondText(“ Hello,world!”,ContentType.Text.Html)}}} .start(wait = true)}运行嵌入式
netty-example 使用Netty的示例Web服务器,受启发例子 public class App { public static void main ( final String [] args ) throws Exception { new WebServer () // Simple GET request .get( " /hello " , ...
netty-examples是基于netty4开发的应用实例:rpc server和client的实现Netty4Client简化netty client的应用,实现自动重连功能RPC HelloWorld 实例服务实现public interface HelloWorld {public Result queryUser...