`
Poechant
  • 浏览: 212724 次
博客专栏
Bebe66e7-3a30-3fc9-aeea-cfa3b474b591
Nginx高性能Web服务...
浏览量:23519
5738817b-23a1-3a32-86de-632d7da73b1e
Cumulus实时媒体服务...
浏览量:21428
社区版块
存档分类
最新评论

Practical Netty (2) CS模式下的Echo及String与ChannelBuffer的转化

 
阅读更多

Practical Netty (2) CS模式下的Echo及String与ChannelBuffer的转化

1. Echo TCP Server

Netty 服务器写多了之后就知道,主要的不同就在于 Handler 的实现。当然 Bootstrap 的不同使用也是有所影响的。


/**
 * EchoTcpServer.java
 */
package test.netty;

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.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

public class EchoTcpServer {
    
    private final int port;
    
    public EchoTcpServer(int port) {
        this.port = port;
    }
    
    public void run() {
        ServerBootstrap sb = new ServerBootstrap(
                new NioServerSocketChannelFactory(
                        Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool()));
        sb.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(new EchoTcpServerHandler());
            }
        });
        sb.bind(new InetSocketAddress(port));
    }
    
    public static void main(String[] args) {
        new EchoTcpServer(28080).run();
    }
}

最关键的自然是 Handler。EchoTcpServerHandler继承SimpleChannelHandler,覆盖messageReceived,参数MessageEvent.getMessage()可以得到 Client 发送来的消息,再调用e.getChannel().write(…)写会给 Client。


/**
 * EchoTcpServerHandler.java
 */
package test.netty;

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 EchoTcpServerHandler extends SimpleChannelHandler {
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
            throws Exception {
        e.getChannel().write(e.getMessage());
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
            throws Exception {
        e.getCause().printStackTrace();
        e.getChannel().close();
    }
}

该 EchoTcpServer,可以通过 Telnet 做客户端来访问。

2. String 与 ChannelBuffer 相互转化

通过ChannelBuffers创建一个ChannelBuffer,然后写入数据。最后再把这个ChannelBuffer写到Channel里。


String msg = "Hello, I'm client.";
ChannelBuffer buffer = ChannelBuffers.buffer(msg.length());
buffer.writeBytes(msg.getBytes());
e.getChannel().write(buffer);

上面MessageEvent.getMessage()得到的是Object,它是一个ChannelBuffer,由于 Client 发送来的是 String,所以它其实是一个 String 啦。怎么把这个 String 给打印到 Server 的终端?用如下的方法:


public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
    ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
    System.out.println(buffer.toString(Charset.defaultCharset()));
}

Reference

  1. http://www.coderli.com/netty-string-channelbuffer
  2. http://netty.io

-

转载请注明来自柳大的CSDN博客:Blog.CSDN.net/Poechant,微博:weibo.com/lauginhom

-

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics