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

news/2024/6/24 17:24:06

<!--new top-->

<!--new top-->

博客专家福利     公告:CSDN博客积分系统升级      有奖试读&征文:我们在互联网上奋斗的故事      参与话题讨论,好礼等你拿      深圳微信开发者大会不容错过的十大理由

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

分类: Lang. - Java 5436人阅读 评论(1) 收藏 举报

目录(?)[+]

  1. Practical Netty 2 CS模式下的Echo及String与ChannelBuffer的转化
    1. Echo TCP Server
    2. String 与 ChannelBuffer 相互转化
    3. Reference

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

  • 作者:柳大·Poechant(钟超)
  • 邮箱:zhongchao.ustc#gmail.com(# -> @)
  • 博客:Blog.CSDN.net/Poechant
  • 微博: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
  2. http://netty.io

-

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


http://www.niftyadmin.cn/n/3959861.html

相关文章

vue2.0学习(四)-实例和内置组件

vue2.0学习(四)-实例和内置组件 1.实例入门-实例属性 一、Vue和Jquery.js一起使用 下载可以去官网进行下载&#xff0c;我这里使用的版本是3.1.1&#xff0c;下载好后在需要的页面引入就可以了。当然你还有很多其它的方法引入jquery&#xff0c;只要可以顺利引入就可以了。 <…

Practical Netty (4) 父子频道关系,频道与管道的关系

Practical Netty (4) 父子频道关系&#xff0c;频道与管道的关系 作者&#xff1a;柳大Poechant&#xff08;钟超&#xff09;邮箱&#xff1a;zhongchao.ustc#gmail.com&#xff08;# -> &#xff09;博客&#xff1a;Blog.CSDN.net/Poechant 微博&#xff1a;weibo.com/la…

开车啦开车啦

目录 结对结对&#xff01;任务要求题目介绍界面界面&#xff01;代码小伙伴介绍结对结对&#xff01; (软件工程第三次作业)[二人结对|极限编程|复查] 任务要求 1.能够自动生成四则运算练习题2. &#xff1a;可以定制题目数量3 &#xff1a;用户设置最大数&#xff08;如十以内…

Think in java 读书笔记

第二章&#xff1a;一切皆对象2.1&#xff1a;类 又称为对象的类型&#xff01;2.2&#xff1a; 本书中&#xff0c;谈到‘类型’都是指class 对象的类型 说的是class &#xff01; new class&#xff08;&#xff09; 是类型实例化出来的对象&#xff01;2.3&#xff1…

Practical Netty (5) TCP反向代理服务器

Practical Netty (5) TCP反向代理服务器 作者&#xff1a;柳大Poechant&#xff08;钟超&#xff09;邮箱&#xff1a;zhongchao.ustc#gmail.com&#xff08;# -> &#xff09;博客&#xff1a;Blog.CSDN.net/Poechant 微博&#xff1a;weibo.com/lauginhom 日期&#xff1a…

Practical Netty (6) HTTP Server/Client

Practical Netty (6) HTTP Server/Client 作者&#xff1a;柳大Poechant&#xff08;钟超&#xff09;邮箱&#xff1a;zhongchao.ustc#gmail.com&#xff08;# -> &#xff09;博客&#xff1a;Blog.CSDN.net/Poechant 微博&#xff1a;weibo.com/lauginhom 日期&#xff1…

51 NOD 1406 and query

我们知道一个数S会对所有它的子集S产生1的贡献&#xff0c;但是我们直接枚举子集是 3^(log2 1000000)的&#xff0c;会炸掉&#xff1b;如果直接把每个有1的位变成0往下推也会凉掉&#xff0c;因为这样会有很多重复的。 但是我们发现 第二种方法其实算的是 有序的路径方案数&am…

java对象的内存计算

我们讨论的是java heap中对象所占内存。 1.基本类型内存占用 类型占用字节数boolean1byte1char2short2int4float4long8double82.对象所占内存由以下部分组成 object header&#xff0c; 8 byte基本类型&#xff0c;见第1节的表格引用类型&#xff0c;都为4 bytepadding&#…