---
title: "Practical Netty (2) CS模式下的Echo及String与ChannelBuffer的转化"
author: "Poechant"
date: "2013-01-02T01:56:00Z"
tags: []
slug: "practical-netty-2-cs-echo-string-channelbuffer"
draft: false
lastmod: "2014-02-06T23:29:29Z"
id: 2011628
url: "https://poechant.iteye.com/blog/2011628"
---

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

- 作者：柳大·Poechant（钟超）
- 邮箱：zhongchao.ustc#gmail.com（# -&gt; @）
- 博客：[Blog.CSDN.net/Poechant](http://blog.csdn.net/Poechant)
- 微博：[weibo.com/lauginhom](http://weibo.com/lauginhom)
- 日期：June 2nd, 2012

## 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](http://www.coderli.com/netty-string-channelbuffer)
2. [http://netty.io](http://netty.io/)

\-

转载请注明来自柳大的CSDN博客：[Blog.CSDN.net/Poechant](http://blog.csdn.net/Poechant)，微博：[weibo.com/lauginhom](http://weibo.com/lauginhom)

\-