一. Server

  1. public class TimeServer_argu {
  2. public void bind(int port) throws InterruptedException {
  3. EventLoopGroup bossGroup = new NioEventLoopGroup(); // 默认开启cpu个数*2个线程
  4. EventLoopGroup workerGroup = new NioEventLoopGroup();
  5. try {
  6. ServerBootstrap server = new ServerBootstrap();
  7. server.group(bossGroup, workerGroup)
  8. .channel(NioServerSocketChannel.class)
  9. .option(ChannelOption.SO_BACKLOG, 128)
  10. .childOption(ChannelOption.SO_KEEPALIVE, true)
  11. .handler(new LoggingHandler(LogLevel.INFO))
  12. .childHandler(new ChannelInitializer<SocketChannel>() {
  13. @Override
  14. public void initChannel(SocketChannel ch) throws Exception {
  15. /* LengthFieldBasedFrameDecoder解码器, 负责解码特定格式报文(开头几个字节表示报文长度), 这个报文长度可以是
  16. 1. 后面真正报文的长度
  17. 2. 也可以是算上长度字段的报文总长度 (此时补偿字段为负)
  18. */
  19. // 报文最大长度,长度字段开始位置偏移量,长度字段所占长度,报文长度的补偿值(netty解析报文首部的长度值,用这个值+补偿值是真正报文的长度),真正报文开始位置的偏移量
  20. ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
  21. /*
  22. LengthFieldPrepender编码器: netty把真正报文转换成Bytebuf发送,这个编码器在Bytebuf的开头加上真正报文的长度
  23. 发送方使用这个编码器,接收方就要使用LengthFieldBasedFrameDecoder解码器来解得真正报文
  24. */
  25. ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
  26. // 用于序列化反序列化对象
  27. //ch.pipeline().addLast("encode", new ObjectEncoder());
  28. // ClassResolvers.weakCachingConcurrentResolver(null)通常用于创建weakhashmap缓存classloader,但ocgi动态替换class,不建议缓存classloader,索引传入null
  29. //ch.pipeline().addLast("decode", new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
  30. ch.pipeline().addLast(new StringDecoder());
  31. ch.pipeline().addLast(new EchoServerHandler());
  32. }
  33. });
  34. ChannelFuture channel = server.bind(port).sync();
  35. channel.channel().closeFuture().sync();
  36. } finally {
  37. workerGroup.shutdownGracefully();
  38. bossGroup.shutdownGracefully();
  39. }
  40. }
  41. private class EchoServerHandler extends ChannelHandlerAdapter {
  42. @Override
  43. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  44. String str = (String) msg;
  45. System.out.println("recieve:"+str);
  46. str = new StringBuilder().append("server recieve ").toString();
  47. ByteBuf byteBuf = Unpooled.copiedBuffer(str.getBytes());
  48. ctx.writeAndFlush(byteBuf);
  49. }
  50. @Override
  51. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  52. cause.printStackTrace();
  53. ctx.close();
  54. }
  55. }
  56. public static void main(String[] args) throws InterruptedException {
  57. new TimeServer_argu().bind(8011);
  58. }
  59. }

二. Client

  1. public class TimeClient_argu {
  2. private static Logger logger = LoggerFactory.getLogger("timeclient-argu");
  3. public static void main(String[] args) {
  4. new TimeClient_argu().connect(8011,"localhost");
  5. }
  6. public void connect(int port,String host){
  7. EventLoopGroup group = new NioEventLoopGroup();
  8. try{
  9. Bootstrap bs = new Bootstrap();
  10. bs.group(group).channel(NioSocketChannel.class)
  11. .option(ChannelOption.TCP_NODELAY,true)
  12. .handler(new ChannelInitializer<SocketChannel>() {
  13. @Override
  14. protected void initChannel(SocketChannel ch) throws Exception { // netty自动识别编码器和解码器放到输入和读取阶段
  15. ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
  16. ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
  17. ch.pipeline().addLast(new StringDecoder());
  18. ch.pipeline().addLast(new EchoClientHandler()); // 打印回显信息
  19. }
  20. });
  21. //发起异步操作链接
  22. ChannelFuture f = bs.connect(host,port).sync();
  23. f.awaitUninterruptibly(10, TimeUnit.SECONDS);
  24. if (!f.isSuccess()) { // 连接不成功记录错误日志
  25. logger.error(f.cause().getMessage());
  26. } else {
  27. f.channel().writeAndFlush(Unpooled.copiedBuffer("query time".getBytes()));
  28. f.channel().closeFuture().sync();
  29. }
  30. f.channel().closeFuture().sync();
  31. } catch (InterruptedException e) {
  32. e.printStackTrace();
  33. } finally {
  34. group.shutdownGracefully();
  35. }
  36. }
  37. private class EchoClientHandler extends ChannelHandlerAdapter {
  38. private int counter;
  39. // 发出的请求报文必须带有"\n"或"\r\n",否则服务端的LineBasedFrameDecoder无法解析
  40. private byte[] req = ("query time").getBytes();
  41. @Override
  42. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  43. String body = (String) msg;
  44. System.out.println("Now : "+ body + "the counter is "+ ++counter);
  45. }
  46. /*@Override
  47. 链接成功后自动发送消息
  48. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  49. ByteBuf msg = null;
  50. for (int i = 0; i < 10; i++) {
  51. msg = Unpooled.buffer(req.length); // 创建指定长度的buf
  52. msg.writeBytes(req);
  53. ctx.writeAndFlush(msg);
  54. }
  55. }*/
  56. @Override
  57. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  58. cause.printStackTrace();
  59. ctx.close();
  60. }
  61. }
  62. }

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. 《C标准库》——之<stddef.h>

    <stddef.h>,顾名思义,就是标准定义.C语言里这个标准库里定义了一些类型,和宏定义. <stddef.h>的内容: 类型: ptrdiff_t : 是两个指针相减的结果 ...

  2. centos6.3 + db2v9.7的数据库移行

    工作内容如题,我要做的事情大体如下: 1,正确备份可用数据库: 2,安装64位的cent os 6.3: 3,将1备份的数据恢复到新的cent os 6.3系统上. 第一件事情,就是备份一个可用的数据 ...

  3. Json学习篇

      JSON的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行 ...

  4. java基础之:匿名内部类应用例子一

    一:接口 package com.yeepay.sxf.testclassforinner; /** * 回调接口. * @author shangxiaofei * */ public interf ...

  5. QueryRunner使用

    在相继学习了JDBC和数据库操作之后,我们明显感到编写JDBC代码并非一件轻松的事儿.为了帮助我们更高效的学习工作,从JDBC的繁重代码中解脱出来,老佟给我们详尽介绍了一个简化JDBC操作的组件——D ...

  6. nginx log记录请求的头信息

    记录访问的log,为了在出现特殊情况时,方便检查出现问题的地方.log_format accesslog ‘$remote_addr – $remote_user [$time_local] “$re ...

  7. javaScript call 函数的用法说明

     call 方法  请参阅 应用于:Function 对象 要求 版本 5.5 调用一个对象的一个方法,以另一个对象替换当前对象. call([thisObj[,arg1[, arg2[, [,.ar ...

  8. 自动生成XML反序列化的类

    原文地址:http://www.cnblogs.com/jaxu/p/3632077.html   Visual Sutdio 2013增加了许多新功能,其中很多都直接提高了对代码编辑的便利性.如: ...

  9. OpenJudge计算概论-与7无关的数

    /*========================================================== 与7无关的数 总时间限制: 1000ms 内存限制: 65536kB 描述 一 ...

  10. OpenJudge计算概论-寻找下标

    /*======================================================================== 寻找下标 总时间限制: 1000ms 内存限制: ...