1.新建一个maven项目,导入Netty所需要的jar包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zc</groupId>
<artifactId>zc-netty-helllo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.25.Final</version>
</dependency>
</dependencies>
</project>
2.新建netty的启动服务程序—>HelloServer类
package com.zc.netty;
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;
/**
* @Author zc
* @Date 2020/4/1 23:36
* @Version 1.0
* @Description 新建netty的启动服务程序
*/
public class HelloServer {
public static void main(String[] args) throws Exception{
//1.定义一对线程组(两个线程池)
//主线程组,用于接收客户端的连接,但是不做任何处理。相当于老板,只接收任务。
EventLoopGroup bossGroup = new NioEventLoopGroup();
//从线程组,老板线程组会把任务丢给他,让手下的工人线程组去做任务。
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//2.netty服务器的创建 创建ServerBootstrap为启动类
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup)//设置主从线程组
.channel(NioServerSocketChannel.class)//设置nio的双向通道
.childHandler(new HelloServerInitializer());//子处理器用于处理workerGroup
//3.启动server,并且设置8088为启动端口号,同时启动方式为同步
ChannelFuture channelFuture = serverBootstrap.bind(8088).sync();
//4.监听关闭的channel,并且设置为同步
channelFuture.channel().closeFuture().sync();
} finally {
//进行优雅的关闭
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
3.初始化一个通道,主要用于设置各种Handler—>HelloServerInitializer类
package com.zc.netty;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
/**
* @Author zc
* @Date 2020/4/2 0:14
* @Version 1.0
* @Description 初始化一个通道,主要用于设置各种Handler
*/
public class HelloServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//通过SocketChannel去获取相对应的管道,可以把这个pipeline理解为拦截器组
ChannelPipeline pipeline = socketChannel.pipeline();
//通过管道添加handler
//HttpServerCodec 是由netty自己提供的助手类,可以理解为拦截器
//当请求到服务端,我们需要做解码,当请求响应到客户端,我们需要做编码。
pipeline.addLast("HttpServerCodec",new HttpServerCodec());
//添加自定义的助手类,返回"hello netty"这样的字符串
pipeline.addLast("customHandler",new CustomHandler());
}
}
4.自定义Handler—>CustomHandler类
package com.zc.netty;
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;
/**
* @Author zc
* @Date 2020/4/2 0:27
* @Version 1.0
* 自定义助手类Handler
*
* 1.客户端发起的请求过来后,先把数据放入缓冲区
* 2.服务端从缓冲区去读数据
* 客户端向服务端发起请求这个过程称为入站
*/
//SimpleChannelInboundHandler:对于请求来讲相当于入站
public class CustomHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg)
throws Exception {
//通过上下文ctx获取channel
Channel channel = ctx.channel();
if(msg instanceof HttpRequest){
//显示远程客户端的地址
System.out.println(channel.remoteAddress());
//定义发送数据的消息
ByteBuf content = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8);
//构建一个http response
DefaultFullHttpResponse response =
new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,//HTTP_1_1默认开启keep-alive长连接,比HTTP_1_0快很多
HttpResponseStatus.OK,
content);
//为响应添加返回数据类型和长度
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
//通过ctx将数据先写到缓冲区然后刷给客户端
ctx.writeAndFlush(response);
}
}
}
**5.启动netty服务端程序HelloServer,进行测试HelloWorld
测试方法一:
启动HelloServer的main方法,在浏览器输入localhost:8088进行测试
测试方法二:
1.通过ipconfig获取windows的主机ip
2.在linux里面输入命令crul ip:8088 进行测试,返回Hello World 成功