Netty是一个Java开源框架,用于传输数据。由server和client组成,封装了Java nio,支持TCP, UDP等协议。这里写了一Demo

  1. EchoClientHandler.java
  1. package chapter1;
  2.  
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.buffer.Unpooled;
  5. import io.netty.channel.ChannelHandler;
  6. import io.netty.channel.ChannelHandlerContext;
  7. import io.netty.channel.SimpleChannelInboundHandler;
  8. import io.netty.util.CharsetUtil;
  9.  
  10. @ChannelHandler.Sharable
  11. public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
  12.  
  13. @Override
  14. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  15. ctx.writeAndFlush(Unpooled.copiedBuffer("hello guanxianseng", CharsetUtil.UTF_8));
  16. }
  17.  
  18. protected void messageReceived(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
  19. System.out.println("Client received:" + msg.toString(CharsetUtil.UTF_8));
  20. System.out.println(msg.toString());
  21. }
  22.  
  23. @Override
  24. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  25. cause.printStackTrace();
  26. ctx.close();
  27. }
  28.  
  29. @Override
  30. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  31. System.out.println("Client received:" + msg.toString());
  32.  
  33. }
  34. }
  1. EchoServer.java
  1. package chapter1;
  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.embedded.EmbeddedChannel;
  9. import io.netty.channel.nio.NioEventLoopGroup;
  10. import io.netty.channel.socket.SocketChannel;
  11. import io.netty.channel.socket.nio.NioServerSocketChannel;
  12.  
  13. import java.net.InetSocketAddress;
  14. import java.util.concurrent.TimeUnit;
  15.  
  16. public class EchoServer {
  17. private int port = 1234;
  18.  
  19. public EchoServer(int port) {
  20. this.port = port;
  21. }
  22.  
  23. public static void main(String[] args) throws Exception{
  24. int port = 1234;
  25. EchoServer echoServer = new EchoServer(port);
  26. schedulTask();
  27. echoServer.start();
  28.  
  29. }
  30.  
  31. public void start() throws Exception{
  32. final EchoServerHandler serverHandler = new EchoServerHandler();
  33. EventLoopGroup group = new NioEventLoopGroup();
  34. try{
  35. ServerBootstrap b = new ServerBootstrap();
  36. b.group(group)
  37. .channel(NioServerSocketChannel.class)
  38. .localAddress(new InetSocketAddress(port))
  39. .childHandler(new ChannelInitializer<SocketChannel>() {
  40. protected void initChannel(SocketChannel ch) throws Exception {
  41. ch.pipeline().addLast(serverHandler);
  42. }
  43. });
  44. ChannelFuture channelFuture = b.bind().sync();
  45. System.out.println("sync test1");
  46. channelFuture.channel().closeFuture().sync();
  47. System.out.println("sync test2");
  48.  
  49. } catch (Exception e){
  50.  
  51. }finally {
  52. group.shutdownGracefully().sync();
  53. System.out.println("sync test3");
  54. }
  55. }
  56.  
  57. public static void schedulTask(){
  58. System.out.println("before test");
  59. Channel ch = new EmbeddedChannel();
  60. ch.eventLoop().scheduleAtFixedRate(new Runnable() {
  61. public void run() {
  62. System.out.println("test");
  63. }
  64. }, 0, 5, TimeUnit.SECONDS);
  65. }
  66. }
  1. EchoClientHandler.java
  1. package chapter1;
  2.  
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.buffer.Unpooled;
  5. import io.netty.channel.ChannelHandler;
  6. import io.netty.channel.ChannelHandlerContext;
  7. import io.netty.channel.SimpleChannelInboundHandler;
  8. import io.netty.util.CharsetUtil;
  9.  
  10. @ChannelHandler.Sharable
  11. public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
  12.  
  13. @Override
  14. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  15. ctx.writeAndFlush(Unpooled.copiedBuffer("hello guanxianseng", CharsetUtil.UTF_8));
  16. }
  17.  
  18. protected void messageReceived(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
  19. System.out.println("Client received:" + msg.toString(CharsetUtil.UTF_8));
  20. System.out.println(msg.toString());
  21. }
  22.  
  23. @Override
  24. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  25. cause.printStackTrace();
  26. ctx.close();
  27. }
  28.  
  29. @Override
  30. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  31. System.out.println("Client received:" + msg.toString());
  32.  
  33. }
  34. }
  1. EchoClient.java
  1. package chapter1;
  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. public class EchoClient {
  14. private String host;
  15. private int port;
  16.  
  17. public EchoClient(String host, int port) {
  18. this.host = host;
  19. this.port = port;
  20. }
  21.  
  22. public static void main(String[] args) throws Exception {
  23. int port = 1234;
  24. String host = "127.0.0.1";
  25. EchoClient echoClient = new EchoClient(host, port);
  26. echoClient.start();
  27. }
  28.  
  29. public void start() throws Exception{
  30. EventLoopGroup group = new NioEventLoopGroup();
  31. try{
  32. Bootstrap b = new Bootstrap();
  33. b.group(group)
  34. .channel(NioSocketChannel.class)
  35. .remoteAddress(new InetSocketAddress(host, port))
  36. .handler(new ChannelInitializer<SocketChannel>() {
  37. protected void initChannel(SocketChannel ch) throws Exception {
  38. ch.pipeline().addLast(new EchoClientHandler());
  39. }
  40. });
  41. ChannelFuture f = b.connect().sync();
  42. f.channel().closeFuture().sync();
  43.  
  44. }catch (Exception e){
  45. e.printStackTrace();
  46. }finally {
  47. group.shutdownGracefully().sync();
  48. }
  49. }
  50. }

netty如何实现各种回调,怎么发送、接收消息,还要看下源码

netty笔记(一)--Demo的更多相关文章

  1. Kubernetes 笔记 02 demo 初体验

    本文首发于我的公众号 Linux云计算网络(id: cloud_dev),专注于干货分享,号内有 10T 书籍和视频资源,后台回复「1024」即可领取,欢迎大家关注,二维码文末可以扫. 从前面的文章我 ...

  2. Netty心跳简单Demo

    前面简单地了解了一下IdleStateHandler,我们现在写一个简单的心跳demo: 1)服务器端每隔5秒检测服务器端的读超时,如果5秒没有接受到客户端的写请求,也就说服务器端5秒没有收到读事件, ...

  3. mybatis笔记<一> Demo

    mybatis作为一个orm互联网公司基本都在用,今天写个笔记.记录一下mybatis使用 参考官网:http://www.mybatis.org/mybatis-3/getting-started. ...

  4. 【Microsoft Azure学习之旅】消息服务Service Bus的学习笔记及Demo示例

    今年项目组做的是Cloud产品,有幸接触到了云计算的知识,也了解并使用了当今流行的云计算平台Amazon AWS与Microsoft Azure.我们的产品最初只部署在AWS平台上,现在产品决定同时支 ...

  5. 【Netty整理01-快速入门】Netty简单使用Demo(已验证)

    多处摘抄或手打,为了十积分厚着脸皮标为原创,惭愧惭愧~本篇文章用于快速入门搭建一个简单的netty 应用,如想稍微深入系统的了解,请参照本人下一篇博客,链接: 参考地址: 官方文档:http://ne ...

  6. 如鹏网仿QQ侧滑菜单:ResideMenu组件的使用笔记整理+Demo

    ResideMenu菜单 课堂笔记: https://github.com/SpecialCyCi/AndroidResideMenu Github:如何使用开源组件1. 下载 下载方式: 1. 项目 ...

  7. Netty的简单Demo

    这个demo是通过网上下载: 使用maven构建的: 项目结构: pom.xml: <dependencies> <dependency> <groupId>io. ...

  8. JavaMail发送邮件的笔记及Demo

    最近碰到一个需求,就是注册用户时候需要向用户发送激活邮箱,于是照着网上搜来的demo自己试着运行了一下,发件时我用的是网易163邮箱,收件时用QQ邮箱,运行后报了一个错误: 网络上搜索解决方式,多次尝 ...

  9. Netty笔记

    1 基本介绍 Bootstrap Netty应用程序通过设置 bootstrap(引导)类开始,该类提供了一个用于应用程序网络层配置的容器.Bootstrap有两种类型,一种是用于客户端的Bootst ...

随机推荐

  1. oracle调试存储过程不进去

    右击存储过程,选中Add debug information即可

  2. 【RMAN备份】数据库备份

    转载请注明地址. 备份片文件名通配符: %c 备份片的拷贝数 %D 位于该月中的第几天 (DD) %M 位于该年中的第几月 (MM) %F 一个基于DBID 唯一的名称,这个格式的形式为c-IIIII ...

  3. 实现bootstrap的dropdown-menu(下拉菜单)点击后不关闭的方法 (转)

    实现bootstrap的dropdown-menu(下拉菜单)点击后不关闭的方法 问题描述,在下拉菜单中,添加其他元素,例如,原文作者所述的<a>和我自己实际用到的<input> ...

  4. java基础_02

    一.this和super 作用: this:区分成员变量和局部变量 super:区分父类的成员变量和局部变量 用法: this.成员变量名://访问本类的成员变量 this.成员方法名()://访问本 ...

  5. HTML <form> target 属性

    浏览器支持 所有主流浏览器都支持 target 属性. 定义和用法 target 属性规定一个名称或一个关键词,指示在何处打开 action URL,即在何处显示提交表单后接收到的响应. target ...

  6. php:// 访问各个输入/输出流

    相关 php.ini 配置 allow_url_fopen :on 默认开启 该选项为on便是激活了 URL 形式的 fopen 封装协议使得可以访问 URL 对象文件等. allow_url_inc ...

  7. 将多个单元格内容连接到一个单元格中(EXCEL)

    连接符号:& 如下图,我们要将表格中每名员工的姓名.入职时间以及年龄放入到同一个单元格中,形成以“-”连接的形式. 这时我们要用到Excel中的连接符“&”,也就是在按下Shift+数 ...

  8. docker 使用save和load命令来转移image

    ——假设一个image叫ubuntu—— 在本机执行sudo docker save -o ubuntu.tar ubuntu 由此得到了 ubuntu.tar 文件,将其拷贝到远程机器,执行 sud ...

  9. 【KMP】【字符串】KMP字符串匹配算法 学习笔记

    一.简介     KMP是由Knuth.Morris和Prat发明的字符串匹配算法,它的时间复杂度是均摊\(O(n+m)\).其实用Hash也可以做到线性,只不过Hash存在极其微小的难以避免的冲突. ...

  10. hdu6183 Color it 线段树动态开点+查询减枝

    题目传送门 题目大意: 有多次操作.操作0是清空二维平面的点,操作1是往二维平面(x,y)上放一个颜色为c的点,操作2是查询一个贴着y轴的矩形内有几种颜色的点,操作3退出程序. 思路: 由于查询的矩形 ...