Netty(2) - HelloWorld
Netty:作用场景。
1)Netty可以基于socket实现远程过程调用(RPC)。
2)Netty可以基于WebSocket实现长连接。
3)Netty可以实现Http的服务器,类似于Jetty,Tomcat等Servlet容器。
-------------------------------------------------------------------------------------------------------------------------------------
Netty充当Http服务器,我们通过浏览器去访问服务器的资源,服务器端处理完之后给我们返回响应-----Helloworld。
-------------------------------------------------------------------------------------------------------------------------------------
1)定义一个Server
1 package com.foreign.netty.helloworld;
2
3 import io.netty.bootstrap.ServerBootstrap;
4 import io.netty.channel.ChannelFuture;
5 import io.netty.channel.EventLoopGroup;
6 import io.netty.channel.nio.NioEventLoopGroup;
7 import io.netty.channel.socket.nio.NioServerSocketChannel;
8
9 /**
10 * Created with IDEA
11 * author:foreign
12 * Date:2018/12/25
13 * Time:23:21
14 */
15 public class TestServer {
16 public static void main(String[] args) throws InterruptedException {
17 /**
18 * 两个事件循环组(死循环) boos接受连接并发送给worker
19 */
20 EventLoopGroup bossLooper = new NioEventLoopGroup();
21 EventLoopGroup workerLooper = new NioEventLoopGroup();
22
23 try {
24 /**
25 * ServerBootstrap 服务端启动
26 * NioServerSocketChannel 通道(反射)
27 */
28 ServerBootstrap serverBootstrap = new ServerBootstrap();
29 serverBootstrap.group(bossLooper, workerLooper).channel(NioServerSocketChannel.class).childHandler(new TestServerInitializer());
30
31 ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
32 channelFuture.channel().closeFuture().sync();
33 } finally {
34 bossLooper.shutdownGracefully();
35 workerLooper.shutdownGracefully();
36 }
37 }
38 }
2)定义一个Initializer
1 package com.foreign.netty.helloworld;
2
3 import io.netty.channel.ChannelInitializer;
4 import io.netty.channel.ChannelPipeline;
5 import io.netty.channel.socket.SocketChannel;
6 import io.netty.handler.codec.http.HttpServerCodec;
7
8 /**
9 * Created with IDEA
10 * author:foreign
11 * Date:2018/12/25
12 * Time:23:32
13 */
14 public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
15
16 /**
17 * 子处理器, channel被注册好,会被自动创建
18 * @param ch
19 * @throws Exception
20 */
21 @Override
22 protected void initChannel(SocketChannel ch) throws Exception {
23 ChannelPipeline pipeline = ch.pipeline();
24 //编解码
25 pipeline.addLast("httpServerCodec",new HttpServerCodec());
26 //自己定义的handler
27 pipeline.addLast("testHttpServerHandler",new TestHttpServerHandler());
28
29 }
30 }
3)定义一个Handler
1 package com.foreign.netty.helloworld;
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 io.netty.handler.codec.http.*;
8 import io.netty.util.CharsetUtil;
9
10 import java.net.URI;
11
12 /**
13 * Created with IDEA
14 * author:foreign
15 * Date:2018/12/25
16 * Time:23:34
17 */
18 public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
19 /**
20 * 把结果返回给客户端(回调)
21 */
22 @Override
23 protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
24 if (msg instanceof HttpRequest) {
25
26 HttpRequest httpRequest = (HttpRequest) msg;
27
28 //获取请求的方法类型
29 System.out.println(httpRequest.method().name());
30
31 URI uri = new URI(httpRequest.uri());
32 if("/favicon.io".equals(uri)) {
33 System.out.println("请求了favicon.io 图标");
34 return;
35 }
36
37 ByteBuf content = Unpooled.copiedBuffer("Hello Netty", CharsetUtil.UTF_8);
38 FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
39 response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
40 response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
41
42 ctx.writeAndFlush(response);
43
44 ctx.channel().close();
45 }
46 }
47 }
4)gradle的配置
plugins {
id 'java'
}
group 'com.foreign'
version '1.0-SNAPSHOT'
apply plugin: 'java'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
implementation 'io.netty:netty-all:4.1.10.Final'
testCompile (
"junit:junit:4.11"
)
}
5)运行结果:运行server,并访问该地址。


6)总结:
1)在TestServer类中,启动一个ServerBootStrap的服务器,里面有两个事件循环组,并且通childHandler关联处理器。
2)在TestServerInitializer中加载netty内置的handler和自己的handler。
3)在TestHttpServerHandler中返回数据到客户端。
7)项目代码:https://github.com/fk123456/Netty/
Netty(2) - HelloWorld的更多相关文章
- Netty(四)分隔符与定长解码器的使用
TCP以流的形式进行数据传输,上层的应用协议为了对消息进行划分,往往采用如下的4种方式. (1)消息长度固定,累计读到长度总和为定长len的报文后,就认为读取到了一个完整的消息:然后重新开始读取下一个 ...
- Netty(二)入门
在上篇<Netty(一)引题>中,分别对AIO,BIO,PIO,NIO进行了简单的阐述,并写了简单的demo.但是这里说的简单,我也只能呵呵了,特别是NIO.AIO(我全手打的,好麻烦). ...
- Wix学习整理(2)——HelloWorld安装添加UI
原文:Wix学习整理(2)--HelloWorld安装添加UI 在前一篇随笔Wix学习整理(1)——快速入门HelloWorld中,我们制作的安装包安装界面太简单,没有与用户进行交互的过程.下面我们修 ...
- Netty(二)——TCP粘包/拆包
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7814644.html 前面讲到:Netty(一)--Netty入门程序 主要内容: TCP粘包/拆包的基础知 ...
- Spring Boot 2.x 快速入门(下)HelloWorld示例详解
上篇 Spring Boot 2.x 快速入门(上)HelloWorld示例 进行了Sprint Boot的快速入门,以实际的示例代码来练手,总比光看书要强很多嘛,最好的就是边看.边写.边记.边展示. ...
- Netty(一)——Netty入门程序
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7447618.html 有兴趣的可先了解下:4种I/O的对比与选型 主要内容包括: Netty开发环境的搭建 ...
- 一起学Netty(一)之 Hello Netty
一起学Netty(一)之 Hello Netty 学习了:https://blog.csdn.net/linuu/article/details/51306480
- 自顶向下深入分析Netty(七)--ChannelPipeline和ChannelHandler总述
自顶向下深入分析Netty(七)--ChannelPipeline和ChannelHandler总述 自顶向下深入分析Netty(七)--ChannelPipeline源码实现 自顶向下深入分析Net ...
- 自顶向下深入分析Netty(六)--Channel总述
自顶向下深入分析Netty(六)--Channel总述 自顶向下深入分析Netty(六)--Channel源码实现 6.1 总述 6.1.1 Channel JDK中的Channel是通讯的载体,而N ...
随机推荐
- React组件设计技巧
React组件设计 组件分类 展示组件和容器组件 展示组件 容器组件 关注事物的展示 关注事物如何工作 可能包含展示和容器组件,并且一般会有DOM标签和css样式 可能包含展示和容器组件,并且不会有D ...
- Spring MVC概述(2)
1.Spring 为展现层提供基于MVC设计理念的优秀的Web框架,是目前最主流的MVC框架之一. 2.Spring 3.0后全面超越Struts2,成为最优秀的MVC框架. 3.Spring MVC ...
- [luoguP1516] 青蛙的约会(扩展欧几里得)
传送门 对于数论只会gcd的我,也要下定决心补数论了 列出方程 (x + t * m) % l = (y + t * n) % l 那么假设 这两个式子之间相差 num 个 l,即为 x + t * ...
- Wow! Such Sequence! (线段树) hdu4893
http://acm.hdu.edu.cn/showproblem.php?pid=4893 先贴上一份还没过的代码,不知道拿出错了 1 // by caonima ; ; ],col[MAX< ...
- graylog 市场
https://marketplace.graylog.org/addons/246dc332-7da7-4016-b2f9-b00f722a8e79
- JavaScript初探之——图片移动
在我们打开页面的时候我们看到的大部分页面都是动态的,曾经学习VB的时候要实现一些动态的画面第一个想到的就是用Flash,如今学习了BS的东西,才算是开眼界了,刚刚学习了一个动画的效果,给大家展示一下. ...
- C#之out和ref区别
out与ref的区别总结:1.两者都是通过引用来传递.2.两者都按地址传递的,使用后都将改变原来参数的数值.3.属性不是变量,因此不能作为 out或ref 参数传递.4.若要使用 ref 或 out, ...
- WingIDE 5.0注冊机
在wingIDE下开发python很方便,但IDE不是免费的,网上有破解的方法.请支持正版. 把下列文件CalcActivationCode.py载入到wingIDE中.LicenseID能够随便给一 ...
- 分布式缓存Redis应用场景解析
Redis的应用场景非常广泛.虽然Redis是一个key-value的内存数据库,但在实际场景中,Redis经常被作为缓存来使用,如面对数据高并发的读写.海量数据的读写等. 举个例子,A网站首页一天有 ...
- UVA - 10691 Subway
题目大意:给定n个点.要求建造尽量少得铁路(从原点发射出的射线).使得全部点到铁路的最短距离小于d. 解题思路:题目能够转化成区间选点问题,即以极角来表示铁轨.然后计算出每一个区间可行的极角范围,进行 ...