netty 入门使用

在网上找了例子:http://blog.csdn.net/bearray123/article/details/6185368,但原例子不知道是不是jar比较旧,有些方法不存在了。所以我也在这提下。之前用过mina,因mina的作者和netty的作者是同一个人,所以对此框架入门比较容易。

 1:下载netty的jar和官方文档:http://www.jboss.org/netty/   。现在的稳定版netty-3.5.10.Final-dist.tar.bz2 刚开始下载的以为只能在Linux上用,后来用360解压发现和平常的压缩包没多区别。

    2:将一个jar(netty-3.5.10.Final.jar)加到项目中,另一个源码包(netty-3.5.10.Final-sources.jar)也可以加进去。

    3: 直接上代码:

MessageClient.java

package com.example;

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 {  
		create();
    }  
	public static void create(){
        String host = "127.0.0.1";  
        int port = 9550;  
        // Configure the client.  
        ClientBootstrap bootstrap = new ClientBootstrap(  
                new NioClientSocketChannelFactory(  
                        Executors.newCachedThreadPool(),  
                        Executors.newCachedThreadPool()));  
        // Set up the event pipeline factory.  
       // bootstrap.setPipelineFactory(new MessageServerPipelineFactory()); 
        bootstrap.getPipeline().addLast("decoder", new MessageDecoder());
        bootstrap.getPipeline().addLast("encoder", new MessageEncoder());
        bootstrap.getPipeline().addLast("handler", new MessageClientHandler());
        // 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.  
      //  future.getChannel().write("我们都是中国人 啊啊!");
        bootstrap.releaseExternalResources();  
	}
}
上面把bootstrap.setPipelineFactory(new MessageServerPipelineFactory()); 给注释掉了,原例子中服务端和客户端共用MessageServerPipelineFactory,但在添加handler的时候,添加的却是服务端的handler,所以是有问题的。要么写两个 MessageServerPipelineFactory类,要么直接像上面那样添加。不能既有MessageServerPipelineFactory,又有bootstrap.getPipeline().addLast()这个方法。

     MessageClientHandler.java

package com.example;

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) {  
        e.getChannel().write(getAString(256));  
    }  
   
    @Override  
    public void messageReceived(  
            ChannelHandlerContext ctx, MessageEvent e) {  
        // Send back the received message to the remote peer.  
        System.out.println("messageReceived send message "+e.getMessage());  
        try {
        	Thread.sleep(3000);
        } catch (InterruptedException e1) {
        	// TODO Auto-generated catch block
        	e1.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();  
    }  
    public String getAString(int size){
    	StringBuilder str = new StringBuilder("");
    	for(int i=0;i<size;i++){
    		str.append("a");
    	}
    	return str.toString();
    }
}  

在channelConnected方法中,当连接到服务器的时候,就开始发送256字节的字符串。当messageReceived接收到服务器的消息时,又把消息发送给服务器。

MessageEncoder.java

package com.example;

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 {
		// TODO Auto-generated method stub
		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;
	}  
   

}  

开始编码:将要发送的字符串转换成字节,数据包头是一个4字节的int,后面就是字符串byte.

MessageDecoder.java

package com.example;

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 {
		// TODO Auto-generated method stub
		 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;  
	}

}
对应前面的编码,先读取4字节的int.如发现不够4字节,则直接返回null,累积到下一次读取。如果发现读取的数据长度不够,则累积到下一次读取。

MessageServer.java

package com.example;

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()); 
	        bootstrap.getPipeline().addLast("decoder", new MessageDecoder());
	        bootstrap.getPipeline().addLast("encoder", new MessageEncoder());
	        bootstrap.getPipeline().addLast("handler", new MessageServerHandler());
	        // Bind and start to accept incoming connections.  
	        bootstrap.bind(new InetSocketAddress(9550));  
	    }  
}

MessageServerHandler.java

package com.example;

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 MessageServerHandler extends SimpleChannelUpstreamHandler{
	   private static final Logger logger = Logger.getLogger(  
	            MessageServerHandler.class.getName());  
	   
	    @Override  
	    public void messageReceived(  
	            ChannelHandlerContext ctx, MessageEvent e) {  
	        e.getChannel().write(e.getMessage());
	    }  
	   
	    @Override  
	    public void exceptionCaught(  
	            ChannelHandlerContext ctx, ExceptionEvent e) {  
	        logger.log(  
	                Level.WARNING,  
	                "Unexpected exception from downstream.",  
	                e.getCause());  
	        e.getChannel().close();  
	    }

		@Override
		public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
				throws Exception {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void channelConnected(ChannelHandlerContext ctx,
				ChannelStateEvent e) throws Exception {
			// TODO Auto-generated method stub
		}
	    
	    
}

MessageServerPipelineFactory.java

package com.example;

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());  

return pipeline;  
}  
}  

上面例子源代码   最后比较了下。mina和netty的性能差不多。但mina比较消耗CPU,netty编解码非常简单。

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值