服务端

NettyServer

  1. package com.zw.netty.config;
  2.  
  3. import com.zw.netty.channel.ServerInitializer;
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelOption;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import io.netty.handler.logging.LogLevel;
    import io.netty.handler.logging.LoggingHandler;
  4.  
  5. /**
    * @author liuzw
    * @email liuzw1@hua-cloud.com.cn
    * @date 2018/12/20 20:39
    */
    public class NettyServer {
  6.  
  7. private final int port;
  8.  
  9. public NettyServer(Integer port){
    this.port = port;
    }
  10.  
  11. public void startServer(){
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);
    b.channel(NioServerSocketChannel.class);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.childHandler(new ServerInitializer());
    b.handler(new LoggingHandler(LogLevel.INFO));
    b.childOption(ChannelOption.AUTO_READ, true);
  12.  
  13. // 服务器绑定端口监听
    ChannelFuture f = b.bind(port).sync();
  14.  
  15. // 监听服务器关闭监听
    f.channel().closeFuture().sync();
  16.  
  17. }catch (InterruptedException e){
  18.  
  19. }finally {
    bossGroup.shutdownGracefully();
    workerGroup.shutdownGracefully();
    }
    }
  20.  
  21. public static void main(String [] args){
    new NettyServer(8081).startServer();
    }
    }

ChannelInitializer

  1. package com.zw.netty.channel;
  2.  
  3. import com.zw.netty.handler.GpsHandler;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelPipeline;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.handler.codec.*;
    import io.netty.handler.codec.string.StringDecoder;
    import io.netty.handler.codec.string.StringEncoder;
    import io.netty.util.CharsetUtil;
  4.  
  5. /**
    * @author liuzw
    * @email liuzw1@hua-cloud.com.cn
    * @date 2018/12/20 20:55
    */
    public class ServerInitializer extends ChannelInitializer<SocketChannel> {
  6.  
  7. @Override
    protected void initChannel(SocketChannel ch) throws Exception {
  8.  
  9. ChannelPipeline pipeline = ch.pipeline();
  10.  
  11. // 以("\n")为结尾分割的 解码器
    // pipeline.addLast("lenth",new FixedLengthFrameDecoder(7));
    // pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    // pipeline.addLast("framer",new DelimiterBasedFrameDecoder(8192, Unpooled.wrappedBuffer(new byte[] { '#' })));
    // pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
    // pipeline.addLast(new LengthFieldPrepender(4));
  12.  
  13. // 字符串解码 和 编码
    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());
  14.  
  15. // 自己的逻辑Handler
    pipeline.addLast("handler", new GpsHandler());
    }
    }
  1.  

ChannelHandler

  1. package com.zw.netty.handler;
  2.  
  3. import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelFutureListener;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.SimpleChannelInboundHandler;
  4.  
  5. import java.net.InetAddress;
    import java.nio.charset.Charset;
    import java.time.LocalDateTime;
  6.  
  7. /**
    * @author liuzw
    * @email liuzw1@hua-cloud.com.cn
    * @date 2018/12/20 21:03
    */
    public class GpsHandler extends SimpleChannelInboundHandler<String> {
  8.  
  9. @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
    System.out.println("RamoteAddress : " + channelHandlerContext.channel().remoteAddress() + " active !");
    System.out.println(s);
    // channelHandlerContext.channel().writeAndFlush("from server;" + LocalDateTime.now());
  10.  
  11. }
  12.  
  13. /**
    * 覆盖 channelActive 方法 在channel被启用的时候触发 (在建立连接的时候)
    *
    * */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("RamoteAddress : " + ctx.channel().remoteAddress() + " active !");
  14.  
  15. }
  16.  
  17. @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
    // 当出现异常就关闭连接
    ctx.close();
    }
    }

客户端

ClientServer

  1. package com.zw.netty;
  2.  
  3. import io.netty.bootstrap.Bootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.nio.NioSocketChannel;
  4.  
  5. /**
    * @author liuzw
    * @email liuzw1@hua-cloud.com.cn
    * @date 2018/12/21 9:49
    */
    public class ClientServer {
  6.  
  7. public static void main(String[] args) {
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
  8.  
  9. bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new MyClientInitializer());
  10.  
  11. try {
    ChannelFuture channelFuture = bootstrap.connect("localhost", 9005).sync();
    channelFuture.channel().closeFuture().sync();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }finally {
    eventLoopGroup.shutdownGracefully();
    }
    }
    }

ChannelInitializer

  1. package com.zw.netty;
  2.  
  3. import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelPipeline;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.handler.codec.FixedLengthFrameDecoder;
    import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
    import io.netty.handler.codec.LengthFieldPrepender;
    import io.netty.handler.codec.string.StringDecoder;
    import io.netty.handler.codec.string.StringEncoder;
    import io.netty.util.CharsetUtil;
  4.  
  5. /**
    * @author liuzw
    * @email liuzw1@hua-cloud.com.cn
    * @date 2018/12/21 9:50
    */
    public class MyClientInitializer extends ChannelInitializer<SocketChannel> {
  6.  
  7. @Override
    protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    // pipeline.addLast(new FixedLengthFrameDecoder(7));
    // pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
    // pipeline.addLast(new LengthFieldPrepender(4));
    pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
    pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
    pipeline.addLast(new MyClientHandler());
    }
  8.  
  9. }

ChannelHandler

  1. package com.zw.netty;
  2.  
  3. import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.SimpleChannelInboundHandler;
  4.  
  5. import java.time.LocalDateTime;
  6.  
  7. /**
    * @author liuzw
    * @email liuzw1@hua-cloud.com.cn
    * @date 2018/12/21 9:52
    */
    public class MyClientHandler extends SimpleChannelInboundHandler<String> {
  8.  
  9. @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    System.out.println(ctx.channel().remoteAddress());
    System.out.println("client output:" + msg);
    ctx.writeAndFlush("from client;" + LocalDateTime.now());
  10.  
  11. }
  12.  
  13. @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    super.exceptionCaught(ctx, cause);
    cause.printStackTrace();
    ctx.channel().close();
    }
  14.  
  15. @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("----------------------");
    // ctx.writeAndFlush("test#");
    ctx.writeAndFlush("test1 ");
    // ctx.writeAndFlush("test11111111111");
    }
  16.  
  17. }
  18.  

netty(二) 创建一个netty服务端和客户端的更多相关文章

  1. 使用PHP创建一个socket服务端

    与常规web开发不同,使用socket开发可以摆脱http的限制.可自定义协议,使用长连接.PHP代码常驻内存等.学习资料来源于workerman官方视频与文档. 通常创建一个socket服务包括这几 ...

  2. [Swift通天遁地]四、网络和线程-(14)创建一个Socket服务端

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...

  3. 利用IDEA创建Web Service服务端和客户端的详细过程

    创建服务端 一.file–>new–>project 二.点击next后输入服务端名,点击finish,生成目录如下 三.在 HelloWorld.Java 文件中右击,选 WebServ ...

  4. Netty(6)源码-服务端与客户端创建

    原生的NIO类图使用有诸多不便,Netty向用户屏蔽了细节,在与用户交界处做了封装. 一.服务端创建时序图 步骤一:创建ServerBootstrap实例 ServerBootstrap是Netty服 ...

  5. 适合新手:从零开发一个IM服务端(基于Netty,有完整源码)

    本文由“yuanrw”分享,博客:juejin.im/user/5cefab8451882510eb758606,收录时内容有改动和修订. 0.引言 站长提示:本文适合IM新手阅读,但最好有一定的网络 ...

  6. Netty 学习(二):服务端与客户端通信

    Netty 学习(二):服务端与客户端通信 作者: Grey 原文地址: 博客园:Netty 学习(二):服务端与客户端通信 CSDN:Netty 学习(二):服务端与客户端通信 说明 Netty 中 ...

  7. Netty学习笔记(二) 实现服务端和客户端

    在Netty学习笔记(一) 实现DISCARD服务中,我们使用Netty和Python实现了简单的丢弃DISCARD服务,这篇,我们使用Netty实现服务端和客户端交互的需求. 前置工作 开发环境 J ...

  8. 常量,字段,构造方法 调试 ms 源代码 一个C#二维码图片识别的Demo 近期ASP.NET问题汇总及对应的解决办法 c# chart控件柱状图,改变柱子宽度 使用C#创建Windows服务 C#服务端判断客户端socket是否已断开的方法 线程 线程池 Task .NET 单元测试的利剑——模拟框架Moq

    常量,字段,构造方法   常量 1.什么是常量 ​ 常量是值从不变化的符号,在编译之前值就必须确定.编译后,常量值会保存到程序集元数据中.所以,常量必须是编译器识别的基元类型的常量,如:Boolean ...

  9. Netty服务端与客户端(源码一)

    首先,整理NIO进行服务端开发的步骤: (1)创建ServerSocketChannel,配置它为非阻塞模式. (2)绑定监听,配置TCP参数,backlog的大小. (3)创建一个独立的I/O线程, ...

随机推荐

  1. MyCat配置详解

    MyCAT 配置解析 server.xml Mycat的配置文件,设置账号.参数等schema.xml Mycat对应的物理数据库和数据库表的配置rule.xml Mycat分片(分库分表)规则 一 ...

  2. fullCalendar使用经验总结

    fullCalendar日历控件官方网址: https://fullcalendar.io/ 1.需要引入的文件 <link href="~/assets/fullcalendar-3 ...

  3. sql server 2016 附加 其它目录的数据库

    如果数据库不在默认目录,那么需要将 mdf所在目录或者 mdf文件 添加 用户 [NT SERVICE\MSSQLSERVER]的创建权限,否则会提示没有权限, 具体详见: https://docs. ...

  4. Java遍历Map对象的方式

    public static void main(String[] args) { HashMap<String, String> testMap = new HashMap<> ...

  5. Optaplanner - 从探究示例中的hello world,初步认识规划引擎的运行步骤。

    上一篇我们成功以把Opotaplanner规划引擎下载回来,并把它的示例运行起来,简单解析了一下它的Cloud balance示例.这一篇我们这些示例的源代码导入到Eclipse中,看看它在后台是怎么 ...

  6. CentOS 7下给nginx安装SSL证书

    0. DNS要能解析你的网址(域名解析和主机解析,例如example.com和www.example.com都要能解析.注意泛解析记录*.example.com可以存在但在本文中暂时无法用于https ...

  7. excel 设置的函数在打开的时候不会自动执行

    excel中设置了个today的函数,显示今天的日期,结果不执行. 解决方案:打开该excel,选择File-->Options  ,在弹出的框框中选择Formulas,在主界面的Calcula ...

  8. Python打包之pyinstaller

    Pyinstaller 进行对应目录下的打包 执行完后请注意建议将该m2的拷贝走 加了参数-w后不会出现黑色控制台的窗子 常用参数说明: –icon=图标路径 -F 打包成一个exe文件 -w 使用窗 ...

  9. DllImport使用

    1.Dll引用路径 (1)exe运行程序所在的目录 (2)System32目录 (3)环境变量目录 (4)自定义路径,如:DllImport(@"C:\OJ\Bin\Judge.dll&qu ...

  10. systemverilog assertion

    1.一般是单独写一个module 里面放assertion,  然后在验证平台顶层和RTL的实例化bind起来​ 2. |->表示直接进行判断,|=>表示下一拍判断,一般一个断言最好只写一 ...