一、Netty服务器搭建步骤

  • 1) 构建一对主从线程池
  • 2) 为服务器设置channel
  • 3) 设置处理从线程池得助手类初始化起
  • 4) 监听启动和关闭服务器

设置Channel初始化器

每一个Channel都是由多个handler共同组成的管道(pipeline),每个管道都类似于一个小助手,需要程序员初始化时自动设置,一个管道可以理解为一个大的拦截器,而里面的handler可以理解为一个小的拦截器。

1. 定义服务启动类

package org.wdzl;import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;/*
实现客户端发送请求,服务器给与响应 hello netty*/
//每次客户端和服务器端连接后都会产生一个Channel对象
public class HelloNettyServer {public static void main(String[] args) throws Exception {//创建一组线程池组//主线程池: 用于接收客户端的请求链接,不做任务处理EventLoopGroup group1 = new NioEventLoopGroup();//从线程池: 主线程组会把任务交给它,让其做任务EventLoopGroup group2 = new NioEventLoopGroup();try{//创建服务器启动类ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(group1, group2) //设置主从线程池.channel(NioServerSocketChannel.class) //设置nio双向通道.childHandler(new HelloNettyServerInitializer()); //添加子处理器,用于处理从线程池交过来的任务//启动服务,并且设置端口号,同时启动的方式为同步ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();//监听关闭的channel,设置为同步方式channelFuture.channel().closeFuture().sync();}finally {group1.shutdownGracefully(); //优雅得进行关闭group2.shutdownGracefully();}}}

2. 定义服务器启动初始化类

package org.wdzl;import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;/*
初始化器,channel注册之后会执行里面的相应的初始化方法*/
public class HelloNettyServerInitializer extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel channel) throws Exception {//通过SocketChannel去获取对应的管道ChannelPipeline pipeline = channel.pipeline();//通过管道添加handler//new HttpServerCodec()是由netty自己提供的助手类,可以理解为拦截器//当请求到服务器,我们需要解码,响应到客户端需要做编码pipeline.addLast("HttpServerCodec", new HttpServerCodec());//添加自定义助手类,给客户端浏览器渲染hello netty~pipeline.addLast("CunstomHandler", new CustomHandler());}
}

3. 自定义Handler

package org.wdzl;import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;/*** 自定义助手类
*/
public class CustomHandler extends SimpleChannelInboundHandler<HttpObject> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {//获取channelChannel channel = ctx.channel();//需要先判断是否是HttpRequest 不然服务器端就会报错if(msg instanceof  HttpRequest){
//在控制台打印远程地址System.out.println(channel.remoteAddress());//定义向客户端发送的数据内容ByteBuf content = Unpooled.copiedBuffer("Hello netty~", CharsetUtil.UTF_8);//构建http response(设置版本号以及状态码)FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.OK, content);//为响应增加数据类型和长度response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());//把响应渲染到html客户端页面上ctx.writeAndFlush(response);}}@Overridepublic void channelRegistered(ChannelHandlerContext ctx) throws  Exception{System.out.println("channel 注册");}@Overridepublic void channelUnregistered(ChannelHandlerContext ctx) throws  Exception{System.out.println("channel 移除");}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws  Exception{System.out.println("channel 活跃");}@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws  Exception{System.out.println("channel不活跃");}@Overridepublic void handlerAdded(ChannelHandlerContext ctx) throws Exception{System.out.println("助手类添加");}@Overridepublic void handlerRemoved(ChannelHandlerContext ctx) throws Exception{System.out.println("助手类移除");}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception{System.out.println("channel 读取完毕");}@Overridepublic void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception{System.out.println("用户事件触发");}@Overridepublic void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception{System.out.println("channel 可写更改");}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception{System.out.println("捕获到异常");}
}

二、Channel的生命周期

Netty服务器搭建相关推荐

  1. Tomcat服务器搭建及测试教程(1),腾讯技术官发布的“神仙文档”火爆网络

    Tomcat是一个免费开源的servlet容器,我们可以在官网获取下载: https://tomcat.apache.org/download-70.cgi 在首页中我们可以根据自己电脑和JDK的不同 ...

  2. Gitea——私有git服务器搭建详细教程

    本文将从源代码和docker安装两种方式带大家从0-1通过Gitea搭建一个私有git服务器 Gitea--私有git服务器搭建教程 什么是Gitea 一.源代码安装方式 1. 前置环境要求 2. 下 ...

  3. CentOS下的DNS服务器搭建

    CentOS下的DNS服务器搭建 实验环境:VMware workstation 10         centos 6.4 说明: DNS是计算机域名系统或域名解析服务器(Domain Name S ...

  4. 使用Linux服务器搭建个人深度学习环境

    使用Linux服务器搭建个人深度学习环境 环境及所需工具 连接服务器 创建自己的python环境 创建深度学习框架的环境(以tensorflow为例) 测试环境 退出环境 删除环境 WinSCP的使用 ...

  5. windows AD/DNS服务器搭建

    windows AD-DS服务器搭建 1 什么是域 2 域的原理及作用 3 使用域的优势 4 Active Directory(活动目录) 5 安装AD条件 6 安装AD步骤 7 DNS服务器 8 D ...

  6. 企业dns服务器搭建

    企业dns服务器搭建 1关于dns的名词解释 2 dns服务的安装与启用 3 高速缓存dns 4 dns的正向解析 5 dns的反向解析 6 dns的双向解析 7 dns集群及更新 8 动态域名解析 ...

  7. -【Java FTP及FTP服务器搭建】

    -[Java FTP及FTP服务器搭建] 一:本文采用apache项目组的 Apache Commons Net™ library 项目地址:http://commons.apache.org/net ...

  8. iis7 文件服务器搭建,iis7 ftp服务器搭建

    iis7 ftp服务器搭建 内容精选 换一换 安装MySQL本文档以"CentOS 6.5 64bit(40GB)"操作系统为例,对应MySQL版本为5.1.73.CentOS 7 ...

  9. SVN服务器搭建--Subversio与TortoiseSVN的配置安装

    SVN服务器搭建和使用(一) Subversion是优秀的版本控制工具,其具体的的优点和详细介绍,这里就不再多说. 首先来下载和搭建SVN服务器. 现在Subversion已经迁移到apache网站上 ...

最新文章

  1. 串口服务器支持多台上位机,RS485多机通信一台上位机两台下位机问题,
  2. 树莓派安装Ubuntu 18 64系统
  3. 「LibreOJ β Round #4」子集
  4. js ajax上传文件到服务器,使用ajax上传并预览图片后传到服务器上
  5. js控制table中tr位置互换
  6. linux日志文件备份,LINUX 自动备份程序日志(shell)
  7. java+ssh+mysql酒店网站管理系统源码
  8. Java按行分割文件
  9. java 的SYSTEM类
  10. linux jdk1.7 tomcat
  11. android 设备实现定时重启(无root权限或已root)
  12. Michio Kaku《Quantum Field Theory: A Modern Introduction》(加来道雄《量子场论:现代导引》)中文目录
  13. 关卡 动画 蓝图 运行_动画蓝图 - Unreal Engine
  14. 《大厂面试》面试官看了直呼想要的简历
  15. 正确理解以下名词及其含义:(1)源程序,目标程序,可执行程序(2)程序编辑,程序编译,程序连接(3)程序,程序模块,程序文件 (4)函数,主函数,被调用函数,库函数
  16. Linux——一文彻底了解进程id和线程id的关系(什么是pid、tgid、lwp、pthread_t)
  17. Pr更新可否又是个传说?
  18. mac 浏览器解决跨域问题
  19. win10下IDEA启动Tomcat乱码 淇℃伅 [main] org.apache.catalina.startup.VersionLoggerListener.log Server.鏈嶅姟鍣ㄧ増鏈
  20. geemap的详细安装步骤及环境配置

热门文章

  1. 我大中华微软MVP中国区人才库
  2. CT/MCT/RMCT算法的学习和实现
  3. 性能测试工具--locust
  4. 已知法线,两向量夹角和一向量,求另一向量
  5. IT行业干什么最赚钱
  6. Xmind8破解教程
  7. 对话 | 汪玉对话周志华:深度学习理论探讨比应用滞后太多
  8. 员工(人才),留得住是因为本身就留得住;留不住的,你永远留不住
  9. 神经网络的激活函数为什么必须使用非线性函数
  10. 在线画html表格,网页表格的各种画法(Html代码)