标签:
Netty是用来做什么的呢,我的理解是它是一个网络开发框架,利用它能很快速方便的开发出高性能的服务端和客户端。刚开始学习java的时候你一定接触过怎么利用socket去实现服务端和客户端,后来java出了NIO这一大利器极大提供了网络程序的性能,但是NIO是基于事件驱动的模型,理解起来比常用的套接字编程要难一点,但是无论是利用NIO还是原始的socket编程从0开始编写一个服务端或是客户端实在是太困难了。Netty就是帮助你去解决这样的问题的,废话不多说先简单介绍一个例子,我们要写一个服务端绑定端口号后,等待客户端的连接,客户端连接后打印一句欢迎语句,然后客户端输入什么,服务端打印出来,并且返回给客户端输出,利用netty实现如下
1 public class Server { 2 3 private ServerBootstrap serverBootstrap; 4 5 private int port; 6 7 public Server(int port) { 8 this.port = port; 9 serverBootstrap = new ServerBootstrap( 10 new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), 11 Executors.newCachedThreadPool())); 12 serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() { 13 public ChannelPipeline getPipeline() throws Exception { 14 ChannelPipeline channelPipeline = Channels.pipeline(); 15 channelPipeline.addLast("decoder", new StringDecoder()); 16 channelPipeline.addLast("encoder", new StringEncoder()); 17 channelPipeline.addLast("serverHandler", new ServerHandler()); 18 return channelPipeline; 19 } 20 }); 21 serverBootstrap.bind(new InetSocketAddress(this.port)); 22 } 23 24 25 private class ServerHandler extends SimpleChannelUpstreamHandler { 26 @Override 27 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { 28 if(e.getMessage() instanceof String) { 29 String message = (String) e.getMessage(); 30 System.out.println("Client Send:" + message); 31 e.getChannel().write("Server receive:" + message); 32 } 33 } 34 35 @Override 36 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { 37 System.out.println("A client connected to this server"); 38 System.out.println("Client:" + e.getChannel().getRemoteAddress()); 39 e.getChannel().write("******************************\r\n"); 40 e.getChannel().write("Welcome to connect this server\r\n"); 41 e.getChannel().write("******************************\r\n"); 42 } 43 } 44 45 public static void main(String args[]) { 46 new Server(9999); 47 } 48 }
标签:
原文地址:http://www.cnblogs.com/kakaleee/p/5487784.html