欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-10 10:17:59
...

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

-