生活随笔
收集整理的這篇文章主要介紹了
Netty初步之hello world
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
http://blog.csdn.net/cxhzqhzq/article/details/6611977
?
Java的網(wǎng)絡(luò)操作一直比較復(fù)雜,雖然說在加入NIO之后簡單了些,但還不是我這些菜鳥玩得起的,由于存在大量低層操作和協(xié)議處理,所以在使用上面還是很難。迄今為止,還沒有用NIO寫出穩(wěn)定可靠的網(wǎng)絡(luò)操作,也許這和具體的應(yīng)用需求較少也有關(guān)系吧。
大概也有人和我對NIO有同樣的想法,他們最NIO進行了一些封裝,所以就有了MIna和現(xiàn)在的Netty。
Netty提供異步的、事件驅(qū)動的網(wǎng)絡(luò)應(yīng)用程序框架和工具,用以快速開發(fā)高性能、高可靠性的網(wǎng)絡(luò)服務(wù)器和客戶端程序[官方定義],整體來看其包含了以下內(nèi)容:
1.提供了豐富的協(xié)議編解碼支持,
2.實現(xiàn)自有的buffer系統(tǒng),減少復(fù)制所帶來的消耗,
3.整套channel的實現(xiàn),
4.基于事件的過程流轉(zhuǎn)以及完整的網(wǎng)絡(luò)事件響應(yīng)與擴展,
5.豐富的example。
有了Netty之后,網(wǎng)絡(luò)編程最起碼會大大簡化,并且我們也不需要為性能問題擔(dān)心,Netty并發(fā)兩三萬還是沒什么太大問題的。已經(jīng)有人進行過實驗了。
本文主要是列舉Netty初步使用的一個最基本的例子,具體的說明在代碼中都有了,所以也不再重復(fù)。
java的學(xué)習(xí)是從Hello word開始的,Netty也從這里開始吧。
這里的例子比較簡單,后面會慢慢的對Netty的一些復(fù)雜應(yīng)用、Netty的原理進行一些解析。
1、ClientThread.java
[java] view plaincopyprint?
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;?????????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()??????{?????????????????????????ClientBootstrap?bootstrap?=?new?ClientBootstrap(??????????????????new?NioClientSocketChannelFactory(??????????????????????????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;??????????????}??????????});???????????????????????????????future?=?bootstrap.connect(new?InetSocketAddress("127.0.0.1",?8080));??????}????????????????????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線程,用來間歇性的發(fā)送消息* @author Ransom*/
public class ClientThread implements Runnable
{private ChannelFuture future;public ChannelFuture getFuture()
{return future;
}public void setFuture(ChannelFuture future)
{this.future = future;
}@Overridepublic void run(){/** 實例化一個客戶端Bootstrap實例,* NioClientSocketChannelFactory是Netty默認提供的。* 兩個參數(shù),一個是boss的線程池,一個是worker執(zhí)行的線程池。* 兩個線程池都使用了java.util.concurrent.Executors中的線程池來創(chuàng)建。*/ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()));/** 設(shè)置piplineFactory,* 顧名思義,就是產(chǎn)生默認的pipline。* pipline的實例是DefaultChannelPipeline* 提供了鏈式的事件通訊機制*/bootstrap.setPipelineFactory(new ChannelPipelineFactory(){/** (non-Javadoc)* @see org.jboss.netty.channel.ChannelPipelineFactory#getPipeline()*/@Overridepublic ChannelPipeline getPipeline() throws Exception{/** 在DefaultChannelPipeline的過濾器 鏈中實現(xiàn)了* encode 、decode、handler* 其中encode實現(xiàn)自ChannelDownstreamHandler接口* decode、Handler實現(xiàn)自ChannelUpstreamHandler接口* 也就說明了在client發(fā)送消息的時候,默認按照順序會先調(diào)用decode* 在client接收到響應(yīng)的時候,會按照順序調(diào)用encode和Handler。* 后面會有文章專門將ChannelDownstreamHandler和ChannelUpstreamHandler的調(diào)用順序。*/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));}/*** 發(fā)送消息至server*/public void sendMsg(){if(future==null) return;String s = "Hello Word!";future.getChannel().write(s);}}
2、Handler.java
[java] view plaincopyprint?
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;???????????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
[java] view plaincopyprint?
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;??????????public?class?Server??{??????public?static?void?main(String[]?args)??????{??????????????????????????????????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服務(wù)* @author Ransom**/
public class Server
{public static void main(String[] args){/** server的注釋和client類似,在這里就不重復(fù)了* 但是需要注意的是server初始化的是ServerBootstrap的實例* client初始化的是ClientBootstrap,兩個是不一樣的。* 里面的channelfactory也是NioServerSocketChannelFactory。*/ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()));bootstrap.setPipelineFactory(new ChannelPipelineFactory(){@Overridepublic 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
[java] view plaincopyprint?
package?HelloWord;????????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)??????????????{????????????????????????????????????e.printStackTrace();??????????????}??????????????r.sendMsg();??????????}???????????????}??}??
總結(jié)
以上是生活随笔為你收集整理的Netty初步之hello world的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。