一. Server

public class TimeServer_argu {

    public void bind(int port) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup(); // 默认开启cpu个数*2个线程
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap server = new ServerBootstrap();
server.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
/* LengthFieldBasedFrameDecoder解码器, 负责解码特定格式报文(开头几个字节表示报文长度), 这个报文长度可以是
1. 后面真正报文的长度
2. 也可以是算上长度字段的报文总长度 (此时补偿字段为负)
*/
// 报文最大长度,长度字段开始位置偏移量,长度字段所占长度,报文长度的补偿值(netty解析报文首部的长度值,用这个值+补偿值是真正报文的长度),真正报文开始位置的偏移量
ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
/*
LengthFieldPrepender编码器: netty把真正报文转换成Bytebuf发送,这个编码器在Bytebuf的开头加上真正报文的长度
发送方使用这个编码器,接收方就要使用LengthFieldBasedFrameDecoder解码器来解得真正报文
*/
ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
// 用于序列化反序列化对象
//ch.pipeline().addLast("encode", new ObjectEncoder());
// ClassResolvers.weakCachingConcurrentResolver(null)通常用于创建weakhashmap缓存classloader,但ocgi动态替换class,不建议缓存classloader,索引传入null
//ch.pipeline().addLast("decode", new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new EchoServerHandler());
}
}); ChannelFuture channel = server.bind(port).sync();
channel.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
} private class EchoServerHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String str = (String) msg;
System.out.println("recieve:"+str);
str = new StringBuilder().append("server recieve ").toString();
ByteBuf byteBuf = Unpooled.copiedBuffer(str.getBytes());
ctx.writeAndFlush(byteBuf);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
} public static void main(String[] args) throws InterruptedException {
new TimeServer_argu().bind(8011);
}
}

二. Client

public class TimeClient_argu {
private static Logger logger = LoggerFactory.getLogger("timeclient-argu"); public static void main(String[] args) {
new TimeClient_argu().connect(8011,"localhost");
} public void connect(int port,String host){
EventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap bs = new Bootstrap();
bs.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY,true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception { // netty自动识别编码器和解码器放到输入和读取阶段
ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new EchoClientHandler()); // 打印回显信息
}
});
//发起异步操作链接
ChannelFuture f = bs.connect(host,port).sync();
f.awaitUninterruptibly(10, TimeUnit.SECONDS);
if (!f.isSuccess()) { // 连接不成功记录错误日志
logger.error(f.cause().getMessage());
} else {
f.channel().writeAndFlush(Unpooled.copiedBuffer("query time".getBytes()));
f.channel().closeFuture().sync();
}
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
} private class EchoClientHandler extends ChannelHandlerAdapter {
private int counter;
// 发出的请求报文必须带有"\n"或"\r\n",否则服务端的LineBasedFrameDecoder无法解析
private byte[] req = ("query time").getBytes(); @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String body = (String) msg;
System.out.println("Now : "+ body + "the counter is "+ ++counter);
} /*@Override
链接成功后自动发送消息
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ByteBuf msg = null;
for (int i = 0; i < 10; i++) {
msg = Unpooled.buffer(req.length); // 创建指定长度的buf
msg.writeBytes(req);
ctx.writeAndFlush(msg);
}
}*/ @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
} }

netty常用代码的更多相关文章

  1. GCD 常用代码

    GCD 常用代码 体验代码 异步执行任务 - (void)gcdDemo1 { // 1. 全局队列 dispatch_queue_t q = dispatch_get_global_queue(0, ...

  2. 转--Android实用的代码片段 常用代码总结

    这篇文章主要介绍了Android实用的代码片段 常用代码总结,需要的朋友可以参考下     1:查看是否有存储卡插入 复制代码 代码如下: String status=Environment.getE ...

  3. 刀哥多线程之03GCD 常用代码

    GCD 常用代码 体验代码 异步执行任务 - (void)gcdDemo1 { // 1. 全局队列 dispatch_queue_t q = dispatch_get_global_queue(0, ...

  4. jquery常用代码集锦

    1. 如何修改jquery默认编码(例如默认GB2312改成 UTF-8 ) 1 2 3 4 5 $.ajaxSetup({     ajaxSettings : {         contentT ...

  5. Mysql:常用代码

    C/S: Client Server B/S: Brower Server Php主要实现B/S .net IIS Jave TomCat LAMP:L Mysql:常用代码 Create table ...

  6. javascript常用代码大全

    http://caibaojian.com/288.html    原文链接 jquery选中radio //如果之前有选中的,则把选中radio取消掉 $("#tj_cat .pro_ca ...

  7. Android 常用代码大集合 [转]

    [Android]调用字符串资源的几种方法   字符串资源的定义 文件路径:res/values/strings.xml 字符串资源定义示例: <?xml version="1.0&q ...

  8. NSIS常用代码整理

    原文 NSIS常用代码整理 这是一些常用的NSIS代码,少轻狂特意整理出来,方便大家随时查看使用.不定期更新哦~~~ 1 ;获取操作系统盘符 2 ReadEnvStr $R0 SYSTEMDRIVE ...

  9. PHP常用代码大全(新手入门必备)

    PHP常用代码大全(新手入门必备),都是一些开发中常用的基础.需要的朋友可以参考下.   1.连接MYSQL数据库代码 <?php $connec=mysql_connect("loc ...

随机推荐

  1. jQuery 事件 - load() 方法

    例子:$("img").load(function(){ $("div").text("Image loaded"); }); 定义和用法 ...

  2. ThinkPHP多表操作

    有以下三张表,分表为pl表(uid,content),user表(id,username),lyb表(uid,title) 多表查询操作有以下几种方法: ㈠视图模型(推荐) 定义视图模型,只需要继承T ...

  3. [AMPPZ 2013]Bytehattan

    先把题目链接贴在这里喵~ http://main.edu.pl/en/archive/amppz/2013/baj 话说真是一道让我严重怀疑我的智商的好题目, 话说此题第一感觉.嗯?似乎离线做做就可以 ...

  4. jquery轻松操作CSS样式

    $(this).click(function(){  if($(this).hasClass(“zxx_fri_on”)){    $(this).removeClass(“zxx_fri_on”); ...

  5. 【转】非常适用的Sourceinsight插件,提高效率事半功倍

    原文网址:http://www.cnblogs.com/wangqiguo/p/3713211.html 一直使用sourceinsight编辑C/C++代码,sourceinsight是一个非常好用 ...

  6. malloc(): memory corruption: 0x0000000001cc7120 ***

    今天在调试一个程序时发生如题所示的错误,在malloc时报错. 经查是由于前面有内存越界,导致内存结构遭到破坏,才发生这样的错误.

  7. ob_start()失效与phpunit的非正常结束

    在ob_clean();或ob_get_clean()之前有return或致命错误,从而结束了程序,会导致ob_start失效, 这和phpunit的非正常结束

  8. memcache中的add和set方法区别

    相信大家对memcache都不陌生,在项目中也经常使用memcache作为缓存方案,那么在使用过程中有没有发现为什么memcahce有两个添加缓存的方法:一个是add,一个是set,那么你知道这2个方 ...

  9. Js文本溢出自动添加省略号ellipsis

    原文: ellipsis: function(value, len, word) {         //判断value有没有超过指定长度         if (value && v ...

  10. 简单实用的Android ORM框架TigerDB

    TigerDB是一个简单的Android ORM框架,它能让你一句话实现数据库的增删改查,同时支持实体对象的持久化和自动映射,同时你也不必关心表结构的变化,因为它会自动检测新增字段来更新你的表结构. ...