`

netty discard 例子

 
阅读更多

// 业务逻辑处理

 

 

package com.bigdata.jboss.basic;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

public class DiscardServerHandler extends SimpleChannelHandler {

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		// do nothing
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		 e.getCause().printStackTrace();
		 e.getChannel().close();
	}

}

   1.DiscardServerHandler 继承 SimpleChannelHandler,提供了事件处理的不同方法。

   2.messageReceived 事件处理方法中的参数MessageEvent,携带了客户端传送过来的参数,在这个例子中,我们实现的        是  DISCARD协议,处理方法是把传送过来的信息丢弃。

   3.exceptionCaught事件处理方法带了ExceptionEvent参数,ExceptionEvent携带了异常信息及连接信息,根据你的业      务   逻辑进行处理,如本例中,输出异常信息及关闭连接。当然,你也可以在关闭连接前,给客户端返回错误编码。

 

//服务器代码

 

package com.bigdata.jboss.basic;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

public class DiscardServer {
	
	public static void main(String[] args) {
		ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool());
		ServerBootstrap bootstrap = new ServerBootstrap(factory);
		
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			
			public ChannelPipeline getPipeline() throws Exception {
				return Channels.pipeline(new DiscardServerHandler());
			} 
		});
		
		bootstrap.setOption("child.tcpNoDelay",true);
		bootstrap.setOption("child.keepAlive", true);
		bootstrap.bind(new InetSocketAddress(8080));
		System.out.println("started discard server");
	}
}

    1. ChannelFactory是创建并管理Channel的工厂,它处理所有I/O请求,及生成I/O ChannelEvent事件。它不创建I/O         线程,它是从构造参数(线程池)中获得线程。

    2.ServerBootstrap是一个帮助类,帮助建立服务。

    3.ChannelPipelineFactory是生成新的连接工厂。

    4.可以给Channel设置参数,如tcpNoDelay,keepAlive,参数需要前缀"child."。

    5.绑定端口8080

 

测试

      telnet localhost 8080

结果:

      服务端无输出

 

为了测试,可以在逻辑处理部分修正如下代码:

 

 

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
          ChannelBuffer buf = (ChannelBuffer) e.getMessage();
          while(buf.readable()) {
          System.out.print((char) buf.readByte());
          System.out.flush();
          }
} 

   1.ChannelBuffer代表了传输的数据结构。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics