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

-

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

钟超

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值