Java教程

Netty实现简单Server(Java)

本文主要是介绍Netty实现简单Server(Java),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

0、前言

在《Idea多模块项目(netty)》中,搭建基本程序框架。

1、先上代码目录

在这里插入图片描述

2、pom文件

<?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>

    <artifactId>com.ct.netty.http</artifactId>
    <version>1.0.0.0</version>
    <packaging>jar</packaging>

    <parent>
        <artifactId>com.ct.netty</artifactId>
        <groupId>com.ct</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
        </dependency>
    </dependencies>

</project>

3、Server启动类

绑定了8088端口。

package com.ct.netty.http.Ijava;

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 LaoHa
 * @Date 2021/6/6
 */
public class HelloServer {
    public static void main(String[] args) {
        //定义主线程组,用于接收客户端请求,但是并不做任何逻辑处理
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //从线程组,主线程组会把相应的请求转交给该线程组,由从线程组去做任务
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        //创建netty服务器
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            //服务器设置绑定两个线程组,并设置相应的助手类【handler】
            serverBootstrap.group(bossGroup, workerGroup)
                    //设置nio双向通道
                    .channel(NioServerSocketChannel.class)
                    //子处理器
                    .childHandler(new HelloServerInitializer());

            //启动server并绑定端口号
            ChannelFuture channelFuture = serverBootstrap.bind(8088).sync();
            //关闭监听的channel
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

4、初始化配置器

package com.ct.netty.http.Ijava;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

/**
 * 初始化配置器,channel注册成功后,会执行里面相应的初始化方法
 *
 * @Author LaoHa
 * @Date 2021/6/6
 */
public class HelloServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        //channel获取相应的管道
        ChannelPipeline pipeline = channel.pipeline();
        //为管道增加相应的handler,可理解为是拦截器,或者监听器,监听客户端建立连接后的信息
        //当请求到服务端,我们需要对写出到客户端的数据做编码处理
        pipeline.addLast("httpCode", new HttpServerCodec());
        //添加自定义助手类,可添加多个
        pipeline.addLast("HelloHandler", new HelloHandler());
    }
}

5、自定义助手句柄处理类

package com.ct.netty.http.Ijava;

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 LaoHa
 * @Date 2021/6/6
 */
public class HelloHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void messageReceived(ChannelHandlerContext context, HttpObject msg)
            throws Exception {
        //通过context的上下文获取channel
        Channel channel = context.channel();
        if (msg instanceof HttpRequest) {
            //获取请求地址
            System.out.println("请求地址:" + channel.remoteAddress());
        }
        //自定义相应客户端信息
        ByteBuf content = Unpooled.copiedBuffer("Hello Netty <<<>>>", CharsetUtil.UTF_8);
        //侯建httpResponse对象
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                content);
        //设置response对象的头信息
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
        //将数据刷到客户端
        context.writeAndFlush(response);
    }
}

6、运行测试

运行HelloServer,启动一下服务端,然后浏览器输入,http://localhost:8088/。
在这里插入图片描述

附录

Netty入门教程——认识Netty

看这一篇入门《Netty入门教程——认识Netty》

这篇关于Netty实现简单Server(Java)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!