ke客户端:

  1. package cn.itcast_03_netty.sendstring.client;
  2.  
  3. import io.netty.bootstrap.Bootstrap;
  4. import io.netty.channel.ChannelFuture;
  5. import io.netty.channel.ChannelInitializer;
  6. import io.netty.channel.EventLoopGroup;
  7. import io.netty.channel.nio.NioEventLoopGroup;
  8. import io.netty.channel.socket.SocketChannel;
  9. import io.netty.channel.socket.nio.NioSocketChannel;
  10.  
  11. import java.net.InetSocketAddress;
  12.  
  13. import cn.itcast_03_netty.sendobject.coder.PersonEncoder;
  14.  
  15. /**
  16. * • 连接服务器 • 写数据到服务器 • 等待接受服务器返回相同的数据 • 关闭连接
  17. *
  18. * @author wilson
  19. *
  20. */
  21. public class EchoClient {
  22.  
  23. private final String host;
  24. private final int port;
  25.  
  26. public EchoClient(String host, int port) {
  27. this.host = host;
  28. this.port = port;
  29. }
  30.  
  31. public void start() throws Exception {
  32. EventLoopGroup nioEventLoopGroup = null;
  33. try {
  34. //不用创建线程池了,内部就有线程池。netty是基于nio开发的。
  35. // 客户端引导类,启动的。
  36. Bootstrap bootstrap = new Bootstrap();
  37. // EventLoopGroup可以理解为是一个线程池的组,这个线程池用来处理连接、接受数据、发送数据
  38. nioEventLoopGroup = new NioEventLoopGroup();
  39. bootstrap.group(nioEventLoopGroup)//多线程处理
  40. .channel(NioSocketChannel.class)//指定通道类型为NioServerSocketChannel,一种异步模式,OIO阻塞模式为OioServerSocketChannel
  41. .remoteAddress(new InetSocketAddress(host, port))//地址
  42. //in handler是进来的,out handler是出去的,
  43. .handler(new ChannelInitializer<SocketChannel>() {//业务处理类
  44. @Override
  45. protected void initChannel(SocketChannel ch)
  46. throws Exception {
  47. ch.pipeline().addLast(new EchoClientHandler());//注册handler
  48. }
  49. });
  50. // 链接服务器
  51. ChannelFuture channelFuture = bootstrap.connect().sync();
  52. channelFuture.channel().closeFuture().sync();
  53. } finally {
  54. nioEventLoopGroup.shutdownGracefully().sync();
  55. }
  56. }
  57.  
  58. public static void main(String[] args) throws Exception {
  59. new EchoClient("localhost", 20000).start();//不是想出的start而是普通的方法
  60. }
  61. }
  1. package cn.itcast_03_netty.sendstring.client;
  2.  
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.buffer.Unpooled;
  5. import io.netty.channel.ChannelHandlerContext;
  6. import io.netty.channel.SimpleChannelInboundHandler;
  7. import cn.itcast_03_netty.sendobject.bean.Person;
  8.  
  9. public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
  10. // 客户端连接服务器后被调用
  11. @Override
  12. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  13. System.out.println("客户端连接服务器,开始发送数据……");
  14. byte[] req = "QUERY TIME ORDER".getBytes();//消息
  15. //nio的buffer
  16. ByteBuf firstMessage = Unpooled.buffer(req.length);//发送类
  17. firstMessage.writeBytes(req);//发送
  18. ctx.writeAndFlush(firstMessage);//flush
  19. }
  20.  
  21. // • 从服务器接收到数据后调用
  22. @Override
  23. protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg)
  24. throws Exception {
  25. System.out.println("client 读取server数据..");
  26. // 服务端返回消息后
  27. ByteBuf buf = (ByteBuf) msg;
  28. byte[] req = new byte[buf.readableBytes()];
  29. buf.readBytes(req);
  30. String body = new String(req, "UTF-8");
  31. System.out.println("服务端数据为 :" + body);
  32. }
  33.  
  34. // • 发生异常时被调用
  35. @Override
  36. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
  37. throws Exception {
  38. System.out.println("client exceptionCaught..");
  39. // 释放资源
  40. ctx.close();
  41. }
  42. }

服务端:

  1. package cn.itcast_03_netty.sendstring.server;
  2.  
  3. import io.netty.bootstrap.ServerBootstrap;
  4. import io.netty.channel.Channel;
  5. import io.netty.channel.ChannelFuture;
  6. import io.netty.channel.ChannelInitializer;
  7. import io.netty.channel.EventLoopGroup;
  8. import io.netty.channel.nio.NioEventLoopGroup;
  9. import io.netty.channel.socket.nio.NioServerSocketChannel;
  10. import cn.itcast_03_netty.sendobject.coder.PersonDecoder;
  11.  
  12. /**
  13. * • 配置服务器功能,如线程、端口 • 实现服务器处理程序,它包含业务逻辑,决定当有一个请求连接或接收数据时该做什么
  14. *
  15. * @author wilson
  16. *
  17. */
  18. public class EchoServer {
  19.  
  20. private final int port;
  21.  
  22. public EchoServer(int port) {
  23. this.port = port;
  24. }
  25.  
  26. public void start() throws Exception {
  27. EventLoopGroup eventLoopGroup = null;
  28. try {
  29. //server端引导类
  30. ServerBootstrap serverBootstrap = new ServerBootstrap();
  31. //连接池处理数据
  32. eventLoopGroup = new NioEventLoopGroup();
  33. //装配bootstrap
  34. serverBootstrap.group(eventLoopGroup)
  35. .channel(NioServerSocketChannel.class)//指定通道类型为NioServerSocketChannel,一种异步模式,OIO阻塞模式为OioServerSocketChannel
  36. .localAddress("localhost",port)//设置InetSocketAddress让服务器监听某个端口已等待客户端连接。
  37. .childHandler(new ChannelInitializer<Channel>() {//设置childHandler执行所有的连接请求
  38. @Override
  39. protected void initChannel(Channel ch) throws Exception {
  40. ch.pipeline().addLast(new EchoServerHandler());//注册handler
  41. }
  42. });
  43. // 最后绑定服务器等待直到绑定完成,调用sync()方法会阻塞直到服务器完成绑定,然后服务器等待通道关闭,因为使用sync(),所以关闭操作也会被阻塞。
  44. ChannelFuture channelFuture = serverBootstrap.bind().sync();
  45. System.out.println("开始监听,端口为:" + channelFuture.channel().localAddress());
  46. channelFuture.channel().closeFuture().sync();
  47. } finally {
  48. eventLoopGroup.shutdownGracefully().sync();
  49. }
  50. }
  51.  
  52. public static void main(String[] args) throws Exception {
  53. new EchoServer(20000).start();
  54. }
  55. }
  1. package cn.itcast_03_netty.sendstring.server;
  2.  
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.buffer.Unpooled;
  5. import io.netty.channel.ChannelHandlerContext;
  6. import io.netty.channel.ChannelInboundHandlerAdapter;
  7.  
  8. import java.util.Date;
  9.  
  10. import cn.itcast_03_netty.sendobject.bean.Person;
  11.  
  12. public class EchoServerHandler extends ChannelInboundHandlerAdapter {
  13.  
  14. @Override
  15. public void channelRead(ChannelHandlerContext ctx, Object msg)
  16. throws Exception {
  17. System.out.println("server 读取数据……");
  18. //读取数据
  19. ByteBuf buf = (ByteBuf) msg;
  20. byte[] req = new byte[buf.readableBytes()];
  21. buf.readBytes(req);
  22. String body = new String(req, "UTF-8");
  23. System.out.println("接收客户端数据:" + body);
  24. //向客户端写数据
  25. System.out.println("server向client发送数据");
  26. String currentTime = new Date(System.currentTimeMillis()).toString();
  27. ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
  28. ctx.write(resp);
  29.  
  30. }
  31.  
  32. @Override
  33. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  34. System.out.println("server 读取数据完毕..");
  35. ctx.flush();//刷新后才将数据发出到SocketChannel
  36. }
  37.  
  38. @Override
  39. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
  40. throws Exception {
  41. cause.printStackTrace();
  42. ctx.close();
  43. }
  44.  
  45. }

Hadoop25---netty,单个handler的更多相关文章

  1. 7.Netty中 handler 的执行顺序

    1.Netty中handler的执行顺序 Handler在Netty中,无疑占据着非常重要的地位.Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码.拦截 ...

  2. netty学习--handler传递

    在netty中的处理链pipeline中,事件是按顺序传递的,把自己拟人为netty程序,针对进来(inbound)的请求,会从head开始,依次往tail传递. pipeline采用了链表结构,he ...

  3. netty(七) Handler的执行顺序

    Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码.拦截指定的报文.统一对日志错误进行处理.统一对 ...

  4. netty之handler write

    转载自:https://blog.csdn.net/FishSeeker/article/details/78447684 实验过,例如channle的handler里有很多个outhandler,在 ...

  5. netty之handler read

    有时候会有一系列的处理in的handler,使用fireChannelRead处理传递 转载自https://blog.csdn.net/u011702633/article/details/8205 ...

  6. 谈谈如何使用Netty开发实现高性能的RPC服务器

    RPC(Remote Procedure Call Protocol)远程过程调用协议,它是一种通过网络,从远程计算机程序上请求服务,而不必了解底层网络技术的协议.说的再直白一点,就是客户端在不必知道 ...

  7. Netty那点事: 概述, Netty中的buffer, Channel与Pipeline

    Netty那点事(一)概述 Netty和Mina是Java世界非常知名的通讯框架.它们都出自同一个作者,Mina诞生略早,属于Apache基金会,而Netty开始在Jboss名下,后来出来自立门户ne ...

  8. Netty开发实现高性能的RPC服务器

    Netty开发实现高性能的RPC服务器 RPC(Remote Procedure Call Protocol)远程过程调用协议,它是一种通过网络,从远程计算机程序上请求服务,而不必了解底层网络技术的协 ...

  9. Netty 启动过程源码分析 (本文超长慎读)(基于4.1.23)

    前言 作为一个 Java 程序员,必须知道Java社区最强网络框架-------Netty,且必须看过源码,才能说是了解这个框架,否则都是无稽之谈.今天楼主不会讲什么理论和概念,而是使用debug 的 ...

随机推荐

  1. .NET开发笔记--对config文件的操作(2)

    1.前台代码 sys_channel_edit.aspx <tbody id="item_box"> <asp:Repeater ID="rptList ...

  2. 《转》openstack中删除虚拟主机,状态一直deleting

    一.我重新启动了该机器.之后想删除没有创建成功的虚拟机(没有打开cpu的vt).结果发现状态一直为deleting状态.在这个状态下创建虚拟机也失败. 二.分析:在/var/log/nova/nova ...

  3. VC中怎么输入特殊符号(如平方、立方等下标符号)

    同在列表控件里显示汉字一样,直接把输入法里特殊字符放进一个数组里,然后再赋值:CString F[]={"m²","∑","±"," ...

  4. 蓝桥杯 第四届C/C++预赛真题(6) 三部排序(水题)

    标题:三部排序 一般的排序有许多经典算法,如快速排序.希尔排序等. 但实际应用时,经常会或多或少有一些特殊的要求.我们没必要套用那些经典算法,可以根据实际情况建立更好的解法. 比如,对一个整型数组中的 ...

  5. flask配置加载几种方式

    方法一.直接配置 app.config['HOST']='xxx.a.com' print(app.config.get('HOST')) 方法二.通过环境变量加载配置 环境变量:export MyA ...

  6. SurvivalShooter学习笔记(六.玩家生命)

    需求: 玩家有初始生命: 被敌人攻击后:掉血,播放受击音效,红屏(用UI图片做)闪烁提示,UI面板刷新生命 直至死亡:死亡播放死亡音效,游戏结束: 1.变量: 玩家生命 public int star ...

  7. ios开源东西

    今天,我们将介绍20个在GitHub上非常受开发者欢迎的iOS开源项目,你准备好了吗? 1. AFNetworking 在众多iOS开源项目中,AFNetworking可以称得上是最受开发者欢迎的库项 ...

  8. CodeForces 668B Little Artem and Dance

    B. Little Artem and Dance time limit per test 2 second memory limit per test 256 megabytes input sta ...

  9. monggodb 模糊查询

    MongoDB的模糊查询其实很简单:      11.LIKE模糊查询userName包含A字母的数据(%A%)       SQL:SELECT * FROM UserInfo WHERE user ...

  10. 巨蟒python全栈开发数据库攻略1:基础攻略

    1.什么是数据库? 2.数据库分类 3.数据库简单介绍 4.安装数据库 5.修改root密码 6.修改字符集 7.sql介绍 8.简单sql操作