netty小试Telnet

 

 

使用netty小时telnet一把,引入netty-3.2.5.Final.jar

 

package netty;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
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 NettyTest {

	public static void main(String[] args) {
		ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
				Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
		
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			public ChannelPipeline getPipeline() throws Exception {
				ChannelPipeline pipeline = Channels.pipeline();
				pipeline.addLast("decoder", new StringDecoder());
				pipeline.addLast("encoder", new StringEncoder());
				
				pipeline.addLast("handle", new TelnetHandle());
				return pipeline;
			}
		});
		
		bootstrap.bind(new InetSocketAddress(9999));
		
		System.err.println("the telnet server is started ....");
	}
}

class TelnetHandle extends SimpleChannelUpstreamHandler {
	private static final Logger logger = Logger.getLogger(  
			TelnetHandle.class.getName());  
  
	private StringBuffer buffer = new StringBuffer();

	private ChannelFuture future;
    @Override  
    public void handleUpstream(  
            ChannelHandlerContext ctx, ChannelEvent e) throws Exception {  
        if (e instanceof ChannelStateEvent) {  
            logger.info(e.toString());  
        }  
        super.handleUpstream(ctx, e);  
    }  
  
    @Override  
    public void channelConnected(  
            ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {  
        // Send greeting for a new connection.  
        e.getChannel().write(  
                "Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");  
        e.getChannel().write("It is " + new Date() + " now.\r\n");  
    }  
  
    @Override  
    public void messageReceived(  
            ChannelHandlerContext ctx, MessageEvent e) {  
  
        // Cast to a String first.  
        // We know it is a String because we put some codec in TelnetPipelineFactory.  
        String request = (String) e.getMessage();  
  
        // Generate and write a response.  
        String response="";  
        boolean close = false;  
        if (request.length() == 0) {  
            response = "Please type something.\r\n";  
        } else if (request.toLowerCase().equals("bye")) {  
            response = "Have a good day!\r\n";  
            close = true;  
        } else if(request.endsWith("\r\n")){  
            response = "Did you say '" + buffer.toString() + "'?\r\n";  
            future = e.getChannel().write(response);  
            buffer.delete(0, buffer.length());
        }else {
        	try {
				buffer.append(new String(request.getBytes("ISO8859-1"),"UTF-8"));
				System.err.println(request);
				System.err.println(new String(request.getBytes("ISO8859-1"),"UTF-8"));
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
        }
  
        // We do not need to write a ChannelBuffer here.  
        // We know the encoder inserted at TelnetPipelineFactory will do the conversion.  
        
  
        // Close the connection after sending 'Have a good day!'  
        // if the client has sent 'bye'.  
        if (close) {  
            future.addListener(ChannelFutureListener.CLOSE);  
        }  
    }  
  
    @Override  
    public void exceptionCaught(  
            ChannelHandlerContext ctx, ExceptionEvent e) {  
        logger.log(  
                Level.WARNING,  
                "Unexpected exception from downstream.",  
                e.getCause());  
        e.getChannel().close();  
    }  
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值