Netty

  • 创建Server服务端

Netty创建全部都是实现自AbstractBootstrap。客户端的是Bootstrap,服务端的则是ServerBootstrap。

  • 创建一个 HelloServer

  1. package org.example.hello;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.EventLoopGroup;
  5. import io.netty.channel.nio.NioEventLoopGroup;
  6. import io.netty.channel.socket.nio.NioServerSocketChannel;
  7. public class HelloServer {
  8. /**
  9. * 服务端监听的端口地址
  10. */
  11. private static final int portNumber = 7878;
  12. public static void main(String[] args) throws InterruptedException {
  13. //创建两个NioEventLoopGroup,一个是父线程(Boss线程),一个是子线程(work线程)
  14. /*父线程组(代码中的parentBosser)担任(acceptor)的角色。负责接收客户端的连接请求,
  15. *处理完成请求,创建一个Channel并注册到子线程组(代码中的childWorker)中的某个线程上面
  16. *,然后这个线程将负责Channel的读写,编解码等操作
  17. */
  18. EventLoopGroup bossGroup = new NioEventLoopGroup();
  19. EventLoopGroup workerGroup = new NioEventLoopGroup();
  20. try {
  21. //实例化一个ServerBootstrap服务端启动引导程序
  22. ServerBootstrap b = new ServerBootstrap();
  23. //设置bootstrap的线程组 目的在于处理Channel中的事件和IO操作
  24. b.group(bossGroup, workerGroup);
  25. //设置Channel类型
  26. b.channel(NioServerSocketChannel.class);
  27. /*设置责任链路 *责任链模式是Netty的核心部分。每个处理者只负责自己有关的东西。然后将处理结果根据责任链*传递下去
  28. */
  29. b.childHandler(new HelloServerInitializer());
  30. // 服务器绑定端口监听
  31. ChannelFuture f = b.bind(portNumber).sync();
  32. // 监听服务器关闭监听
  33. f.channel().closeFuture().sync();
  34. // 可以简写为
  35. /* b.bind(portNumber).sync().channel().closeFuture().sync(); */
  36. } finally {
  37. bossGroup.shutdownGracefully();
  38. workerGroup.shutdownGracefully();
  39. }
  40. }
  41. }

EventLoopGroup 是在4.x版本中提出来的一个新概念。用于channel的管理。服务端需要两个。和3.x版本一样,一个是boss线程一个是worker线程。

b.childHandler(new HelloServerInitializer());    //用于添加相关的Handler

服务端简单的代码,真的没有办法在精简了感觉。就是一个绑定端口操作。

  • 创建和实现HelloServerInitializer

  在HelloServer中的HelloServerInitializer在这里实现。

  首先我们需要明确我们到底是要做什么的。很简单。HelloWorld!。我们希望实现一个能够像服务端发送文字的功能。服务端假如可以最好还能返回点消息给客户端,然客户端去显示。



  需求简单。那我们下面就准备开始实现。



  DelimiterBasedFrameDecoder Netty在官方网站上提供的示例显示 有这么一个解码器可以简单的消息分割。



  其次 在decoder里面我们找到了String解码编码器。着都是官网提供给我们的

  1. package org.example.hello;
  2. import io.netty.channel.ChannelInitializer;
  3. import io.netty.channel.ChannelPipeline;
  4. import io.netty.channel.socket.SocketChannel;
  5. import io.netty.handler.codec.DelimiterBasedFrameDecoder;
  6. import io.netty.handler.codec.Delimiters;
  7. import io.netty.handler.codec.string.StringDecoder;
  8. import io.netty.handler.codec.string.StringEncoder;
  9. public class HelloServerInitializer extends ChannelInitializer<SocketChannel> {
  10. @Override
  11. protected void initChannel(SocketChannel ch) throws Exception {
  12. ChannelPipeline pipeline = ch.pipeline();
  13. // 以("\n")为结尾分割的 解码器
  14. pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
  15. // 字符串解码 和 编码
  16. pipeline.addLast("decoder", new StringDecoder());
  17. pipeline.addLast("encoder", new StringEncoder());
  18. // 自己的逻辑Handler
  19. pipeline.addLast("handler", new HelloServerHandler());
  20. }
  21. }
  • 增加自己的逻辑HelloServerHandler

自己的Handler我们这里先去继承extends官网推荐的SimpleChannelInboundHandler 。在这里C,由于我们需求里面发送的是字符串。这里的C改写为String。

  1. package org.example.hello;
  2. import java.net.InetAddress;
  3. import io.netty.channel.ChannelHandlerContext;
  4. import io.netty.channel.SimpleChannelInboundHandler;
  5. public class HelloServerHandler extends SimpleChannelInboundHandler<String> {
  6. @Override
  7. protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
  8. // 收到消息直接打印输出
  9. System.out.println(ctx.channel().remoteAddress() + " Say : " + msg);
  10. // 返回客户端消息 - 我已经接收到了你的消息
  11. ctx.writeAndFlush("Received your message !\n");
  12. }
  13. /*
  14. *
  15. * 覆盖 channelActive 方法 在channel被启用的时候触发 (在建立连接的时候)
  16. *
  17. * channelActive 和 channelInActive 在后面的内容中讲述,这里先不做详细的描述
  18. * */
  19. @Override
  20. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  21. System.out.println("RamoteAddress : " + ctx.channel().remoteAddress() + " active !");
  22. ctx.writeAndFlush( "Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n");
  23. super.channelActive(ctx);
  24. }
  25. }

 在channelHandlerContent自带一个writeAndFlush方法。方法的作用是写入Buffer并刷入。



  注意:在3.x版本中此处有很大区别。在3.x版本中write()方法是自动flush的。在4.x版本的前面几个版本也是一样的。但是在4.0.9之后修改为WriteAndFlush。普通的write方法将不会发送消息。需要手动在write之后flush()一次这里channeActive的意思是当连接活跃(建立)的时候触发.输出消息源的远程地址。并返回欢迎消息。



  channelRead0 在这里的作用是类似于3.x版本的messageReceived()。可以当做是每一次收到消息是触发。我们在这里的代码是返回客户端一个字符串"Received your message !".



  注意:字符串最后面的"\n"是必须的。因为我们在前面的解码器DelimiterBasedFrameDecoder是一个根据字符串结尾为“\n”来结尾的。假如没有这个字符的话。解码会出现问题。

  

创建Client客户端

  1. package org.example.hello;
  2. import io.netty.bootstrap.Bootstrap;
  3. import io.netty.channel.Channel;
  4. import io.netty.channel.EventLoopGroup;
  5. import io.netty.channel.nio.NioEventLoopGroup;
  6. import io.netty.channel.socket.nio.NioSocketChannel;
  7. import java.io.BufferedReader;
  8. import java.io.IOException;
  9. import java.io.InputStreamReader;
  10. public class HelloClient {
  11. public static String host = "127.0.0.1";
  12. public static int port = 7878;
  13. /**
  14. * @param args
  15. * @throws InterruptedException
  16. * @throws IOException
  17. */
  18. public static void main(String[] args) throws InterruptedException, IOException {
  19. EventLoopGroup group = new NioEventLoopGroup();
  20. try {
  21. Bootstrap b = new Bootstrap();
  22. b.group(group)
  23. .channel(NioSocketChannel.class)
  24. .handler(new HelloClientInitializer());
  25. // 连接服务端
  26. Channel ch = b.connect(host, port).sync().channel();
  27. // 控制台输入
  28. BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  29. for (;;) {
  30. String line = in.readLine();
  31. if (line == null) {
  32. continue;
  33. }
  34. /*
  35. * 向服务端发送在控制台输入的文本 并用"\r\n"结尾
  36. * 之所以用\r\n结尾 是因为我们在handler中添加了 DelimiterBasedFrameDecoder 帧解码。
  37. * 这个解码器是一个根据\n符号位分隔符的解码器。所以每条消息的最后必须加上\n否则无法识
  38. 别和解码
  39. * */
  40. ch.writeAndFlush(line + "\r\n");
  41. }
  42. } finally {
  43. // The connection is closed automatically on shutdown.
  44. group.shutdownGracefully();
  45. }
  46. }
  47. }
  • HelloClientInitializer

  1. package org.example.hello;
  2. import io.netty.channel.ChannelInitializer;
  3. import io.netty.channel.ChannelPipeline;
  4. import io.netty.channel.socket.SocketChannel;
  5. import io.netty.handler.codec.DelimiterBasedFrameDecoder;
  6. import io.netty.handler.codec.Delimiters;
  7. import io.netty.handler.codec.string.StringDecoder;
  8. import io.netty.handler.codec.string.StringEncoder;
  9. public class HelloClientInitializer extends ChannelInitializer<SocketChannel> {
  10. @Override
  11. protected void initChannel(SocketChannel ch) throws Exception {
  12. ChannelPipeline pipeline = ch.pipeline();
  13. /*
  14. * 这个地方的 必须和服务端对应上。否则无法正常解码和编码
  15. *
  16. * 解码和编码 我将会在下一张为大家详细的讲解。再次暂时不做详细的描述
  17. *
  18. * */
  19. pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
  20. pipeline.addLast("decoder", new StringDecoder());
  21. pipeline.addLast("encoder", new StringEncoder());
  22. // 客户端的逻辑
  23. pipeline.addLast("handler", new HelloClientHandler());
  24. }
  25. }
  • HelloClientHandler

  1. package org.example.hello;
  2. import io.netty.channel.ChannelHandlerContext;
  3. import io.netty.channel.SimpleChannelInboundHandler;
  4. public class HelloClientHandler extends SimpleChannelInboundHandler<String> {
  5. @Override
  6. protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
  7. System.out.println("Server say : " + msg);
  8. }
  9. @Override
  10. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  11. System.out.println("Client active ");
  12. super.channelActive(ctx);
  13. }
  14. @Override
  15. public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  16. System.out.println("Client close ");
  17. super.channelInactive(ctx);
  18. }
  19. }

Netty创建服务器与客户端的更多相关文章

  1. node.js中使用http模块创建服务器和客户端

    node.js中的 http 模块提供了创建服务器和客户端的方法,http 全称是超文本传输协议,基于 tcp 之上,属于应用层协议. 一.创建http服务器 const http = require ...

  2. node.js中net模块创建服务器和客户端(TCP)

    node.js中net模块创建服务器和客户端 1.node.js中net模块创建服务器(net.createServer) // 将net模块 引入进来 var net = require(" ...

  3. Netty——简单创建服务器、客户端通讯

    Netty 是一个基于NIO的客户.服务器端编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户,服务端应用.Netty相当简化和流线化了网络应用的编程开发过程 ...

  4. node.js在windows下的学习笔记(5)---用NODE.JS创建服务器和客户端

    //引入http模块 var http = require('http'); //调用http的createServer的方法,这个方法有一个回调函数,这个回调数 //的作用是当有请求发送给服务器的时 ...

  5. Netty入门(二)时间服务器及客户端

    在这个例子中,我在服务器和客户端连接被创立时发送一个消息,然后在客户端解析收到的消息并输出.并且,在这个项目中我使用 POJO 代替 ByteBuf 来作为传输对象. 一.服务器实现 1.  首先我们 ...

  6. netty源码解解析(4.0)-20 ChannelHandler: 自己实现一个自定义协议的服务器和客户端

    本章不会直接分析Netty源码,而是通过使用Netty的能力实现一个自定义协议的服务器和客户端.通过这样的实践,可以更深刻地理解Netty的相关代码,同时可以了解,在设计实现自定义协议的过程中需要解决 ...

  7. netty系列之:搭建客户端使用http1.1的方式连接http2服务器

    目录 简介 使用http1.1的方式处理http2 处理TLS连接 处理h2c消息 发送消息 总结 简介 对于http2协议来说,它的底层跟http1.1是完全不同的,但是为了兼容http1.1协议, ...

  8. 可以创建专业的客户端/服务器视频会议应用程序的音频和视频控件LEADTOOLS Video Conferencing SDK

    LEADTOOLS Video Streaming Module控件为您创建一个自定义的视频会议应用程序和工具提供所有需要的功能.软件开发人员可以使用Video Streaming Module SD ...

  9. Node.js权威指南 (8) - 创建HTTP与HTTPS服务器及客户端

    8.1 HTTP服务器 / 177 8.1.1 创建HTTP服务器 / 177 8.1.2 获取客户端请求信息 / 182 8.1.3 转换URL字符串与查询字符串 / 184 8.1.4 发送服务器 ...

随机推荐

  1. [Luogu3797] 妖梦斩木棒

    题目背景 妖梦是住在白玉楼的半人半灵,拥有使用剑术程度的能力. 题目描述 有一天,妖梦正在练习剑术.地面上摆放了一支非常长的木棒,妖梦把它们切成了等长的n段.现在这个木棒可以看做由三种小段构成,中间的 ...

  2. caffe中softmax源码阅读

    (1) softmax函数                                      (1) 其中,zj 是softmax层的bottom输入, f(zj)是softmax层的top输 ...

  3. POJ 3020 Antenna Placement(二分图 匈牙利算法)

    题目网址:  http://poj.org/problem?id=3020 题意: 用椭圆形去覆盖给出所有环(即图上的小圆点),有两种类型的椭圆形,左右朝向和上下朝向的,一个椭圆形最多可以覆盖相邻的两 ...

  4. ElasticSearch Bulk API

    做一个简单的记录,以便自己后续查找 一.环境要求 ElasticSearch 7.3.0 Kibana 7.3.0 二.详情 ElasticSearch 的 Bulk API 可以批量进行索引或者删除 ...

  5. QLable 显示图片

    1,各种对就是不显示,因为路径中有其它符号如\n\r什么的 QStringList FileOpeartion::PathCombine (const QString strPath, QString ...

  6. SpringCloud - 概述

    Spring Cloud 什么是Spring Cloud ? SpringCloud是基于SpringBoot提供的一套一站式微服务解决方案,包括服务注册与发现(Eureka), 配置中心(Sprin ...

  7. kafka里的一些管理脚本

    kafka-server-start脚本 ------启动kafka server kafka-server-stop脚本 ------关闭kafka server kafka-topics脚本 -- ...

  8. (day30)GIL + 线程相关知识点

    目录 昨日内容 进程互斥锁 队列 进程间通信 生产者与消费者模型 线程 什么是线程 为什么使用线程 创建线程的两种方式 线程对象的属性 线程互斥锁 今日内容 GIL全局解释器锁 多线程的作用 计算密集 ...

  9. 基于redis解决session分布式一致性问题

    1.session是什么 当用户在前端发起请求时,服务器会为当前用户建立一个session,服务器将sessionId回写给客户端,只要用户浏览器不关闭,再次请求服务器时,将sessionId传给服务 ...

  10. 并发中如何保证缓存DB双写一致性(JAVA栗子)

    并发场景中大部分处理的是先更新DB,再(删缓.更新)缓存的处理方式,但是在实际场景中有可能DB更新成功了,但是缓存设置失败了,就造成了缓存与DB数据不一致的问题,下面就以实际情况说下怎么解决此类问题. ...