我是靠谱客的博主 着急秋天,最近开发中收集的这篇文章主要介绍手写最简版Netty,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

  • 学习源码是netty-all:4.1.52.Finar,阅读此源码,手写一个最简版的Netty,帮助自己理解netty设计思想。
  • 手写实现的Netty源码(包含服务器demo和客户端demo)
    netty-starter.zip
  • 项目目录结构如下图
    在这里插入图片描述
  • netty-starter/pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <packaging>pom</packaging>
    <modules>
        <module>netty-all</module>
        <module>echo-server</module>
        <module>echo-client</module>
    </modules>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>io.netty</groupId>
    <artifactId>netty-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>netty-starter</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

  • netty-all/pom.xml
<?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">
    <parent>
        <artifactId>netty-starter</artifactId>
        <groupId>io.netty</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>netty-all</artifactId>

    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
    </properties>

</project>

  • 服务端echo-server使用demo
package com.zhiguo.netty;

import com.zhiguo.handler.ServerChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * NettyServer
 *
 * @author: liuzhiguo
 * @date: 2021/9/21 14:18
 */
@Slf4j
@Data
@Component
public class NettyServer implements CommandLineRunner {
    @Value("${netty.port}")
    private int port;
    @Autowired
    private ServerChannelInitializer serverChannelInitializer;

    @Override
    public void run(String... args) throws Exception {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.childHandler(serverChannelInitializer);
            serverBootstrap.bind(port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  • 客户端echo-client使用demo
package com.zhiguo.netty;

import com.zhiguo.handler.ClientChannelInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * NettyClient
 *
 * @author: liuzhiguo
 * @date: 2021/9/21 16:02
 */
@Slf4j
@Data
@Component
public class NettyClient implements CommandLineRunner {

    @Value("${netty.host}")
    private String host;
    @Value("${netty.port}")
    private int port;

    @Autowired
    private ClientChannelInitializer clientChannelInitializer;

    @Override
    public void run(String... args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup(1);

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class);
        bootstrap.handler(clientChannelInitializer);
        bootstrap.connect(host, port);
    }

}

  • 服务端启动控制台输出
"C:Program FilesJavajdk1.8.0_181binjava.exe" -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always "-javaagent:C:Program FilesJetBrainsIntelliJ IDEA 2021.1.3libidea_rt.jar=56861:C:Program FilesJetBrainsIntelliJ IDEA 2021.1.3bin" -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true -Dfile.encoding=UTF-8 -classpath "C:Program FilesJavajdk1.8.0_181jrelibcharsets.jar;C:Program FilesJavajdk1.8.0_181jrelibdeploy.jar;C:Program FilesJavajdk1.8.0_181jrelibextaccess-bridge-64.jar;C:Program FilesJavajdk1.8.0_181jrelibextcldrdata.jar;C:Program FilesJavajdk1.8.0_181jrelibextdnsns.jar;C:Program FilesJavajdk1.8.0_181jrelibextjaccess.jar;C:Program FilesJavajdk1.8.0_181jrelibextjfxrt.jar;C:Program FilesJavajdk1.8.0_181jrelibextlocaledata.jar;C:Program FilesJavajdk1.8.0_181jrelibextnashorn.jar;C:Program FilesJavajdk1.8.0_181jrelibextsunec.jar;C:Program FilesJavajdk1.8.0_181jrelibextsunjce_provider.jar;C:Program FilesJavajdk1.8.0_181jrelibextsunmscapi.jar;C:Program FilesJavajdk1.8.0_181jrelibextsunpkcs11.jar;C:Program FilesJavajdk1.8.0_181jrelibextzipfs.jar;C:Program FilesJavajdk1.8.0_181jrelibjavaws.jar;C:Program FilesJavajdk1.8.0_181jrelibjce.jar;C:Program FilesJavajdk1.8.0_181jrelibjfr.jar;C:Program FilesJavajdk1.8.0_181jrelibjfxswt.jar;C:Program FilesJavajdk1.8.0_181jrelibjsse.jar;C:Program FilesJavajdk1.8.0_181jrelibmanagement-agent.jar;C:Program FilesJavajdk1.8.0_181jrelibplugin.jar;C:Program FilesJavajdk1.8.0_181jrelibresources.jar;C:Program FilesJavajdk1.8.0_181jrelibrt.jar;D:giteenetty-starterecho-servertargetclasses;D:giteenetty-starternetty-alltargetclasses;C:UsersAdmin.m2repositoryorgspringframeworkbootspring-boot-starter2.3.4.RELEASEspring-boot-starter-2.3.4.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkbootspring-boot2.3.4.RELEASEspring-boot-2.3.4.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-context5.2.9.RELEASEspring-context-5.2.9.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-aop5.2.9.RELEASEspring-aop-5.2.9.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-beans5.2.9.RELEASEspring-beans-5.2.9.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-expression5.2.9.RELEASEspring-expression-5.2.9.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkbootspring-boot-autoconfigure2.3.4.RELEASEspring-boot-autoconfigure-2.3.4.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkbootspring-boot-starter-logging2.3.4.RELEASEspring-boot-starter-logging-2.3.4.RELEASE.jar;C:UsersAdmin.m2repositorychqoslogbacklogback-classic1.2.3logback-classic-1.2.3.jar;C:UsersAdmin.m2repositorychqoslogbacklogback-core1.2.3logback-core-1.2.3.jar;C:UsersAdmin.m2repositoryorgapachelogginglog4jlog4j-to-slf4j2.13.3log4j-to-slf4j-2.13.3.jar;C:UsersAdmin.m2repositoryorgapachelogginglog4jlog4j-api2.13.3log4j-api-2.13.3.jar;C:UsersAdmin.m2repositoryorgslf4jjul-to-slf4j1.7.30jul-to-slf4j-1.7.30.jar;C:UsersAdmin.m2repositoryjakartaannotationjakarta.annotation-api1.3.5jakarta.annotation-api-1.3.5.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-core5.2.9.RELEASEspring-core-5.2.9.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-jcl5.2.9.RELEASEspring-jcl-5.2.9.RELEASE.jar;C:UsersAdmin.m2repositoryorgyamlsnakeyaml1.26snakeyaml-1.26.jar;C:UsersAdmin.m2repositoryorgprojectlomboklombok1.18.12lombok-1.18.12.jar;C:UsersAdmin.m2repositoryorgslf4jslf4j-api1.7.30slf4j-api-1.7.30.jar" com.zhiguo.EchoServerApplication

  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _    
( ( )___ | '_ | '_| | '_ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |___, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.4.RELEASE)

2021-10-12 10:23:14.517  INFO 5412 --- [           main] com.zhiguo.EchoServerApplication         : Starting EchoServerApplication on PS-12 with PID 5412 (D:giteenetty-starterecho-servertargetclasses started by Admin in D:giteenetty-starter)
2021-10-12 10:23:14.520  INFO 5412 --- [           main] com.zhiguo.EchoServerApplication         : No active profile set, falling back to default profiles: default
2021-10-12 10:23:14.919  INFO 5412 --- [           main] com.zhiguo.EchoServerApplication         : Started EchoServerApplication in 0.735 seconds (JVM running for 1.402)
服务端开放端口:0.0.0.0/0.0.0.0:8008
EchoServer read:nihao

  • 客户端启动控制台输出
"C:Program FilesJavajdk1.8.0_181binjava.exe" -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always "-javaagent:C:Program FilesJetBrainsIntelliJ IDEA 2021.1.3libidea_rt.jar=56976:C:Program FilesJetBrainsIntelliJ IDEA 2021.1.3bin" -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true -Dfile.encoding=UTF-8 -classpath "C:Program FilesJavajdk1.8.0_181jrelibcharsets.jar;C:Program FilesJavajdk1.8.0_181jrelibdeploy.jar;C:Program FilesJavajdk1.8.0_181jrelibextaccess-bridge-64.jar;C:Program FilesJavajdk1.8.0_181jrelibextcldrdata.jar;C:Program FilesJavajdk1.8.0_181jrelibextdnsns.jar;C:Program FilesJavajdk1.8.0_181jrelibextjaccess.jar;C:Program FilesJavajdk1.8.0_181jrelibextjfxrt.jar;C:Program FilesJavajdk1.8.0_181jrelibextlocaledata.jar;C:Program FilesJavajdk1.8.0_181jrelibextnashorn.jar;C:Program FilesJavajdk1.8.0_181jrelibextsunec.jar;C:Program FilesJavajdk1.8.0_181jrelibextsunjce_provider.jar;C:Program FilesJavajdk1.8.0_181jrelibextsunmscapi.jar;C:Program FilesJavajdk1.8.0_181jrelibextsunpkcs11.jar;C:Program FilesJavajdk1.8.0_181jrelibextzipfs.jar;C:Program FilesJavajdk1.8.0_181jrelibjavaws.jar;C:Program FilesJavajdk1.8.0_181jrelibjce.jar;C:Program FilesJavajdk1.8.0_181jrelibjfr.jar;C:Program FilesJavajdk1.8.0_181jrelibjfxswt.jar;C:Program FilesJavajdk1.8.0_181jrelibjsse.jar;C:Program FilesJavajdk1.8.0_181jrelibmanagement-agent.jar;C:Program FilesJavajdk1.8.0_181jrelibplugin.jar;C:Program FilesJavajdk1.8.0_181jrelibresources.jar;C:Program FilesJavajdk1.8.0_181jrelibrt.jar;D:giteenetty-starterecho-clienttargetclasses;D:giteenetty-starternetty-alltargetclasses;C:UsersAdmin.m2repositoryorgspringframeworkbootspring-boot-starter2.3.4.RELEASEspring-boot-starter-2.3.4.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkbootspring-boot2.3.4.RELEASEspring-boot-2.3.4.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-context5.2.9.RELEASEspring-context-5.2.9.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-aop5.2.9.RELEASEspring-aop-5.2.9.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-beans5.2.9.RELEASEspring-beans-5.2.9.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-expression5.2.9.RELEASEspring-expression-5.2.9.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkbootspring-boot-autoconfigure2.3.4.RELEASEspring-boot-autoconfigure-2.3.4.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkbootspring-boot-starter-logging2.3.4.RELEASEspring-boot-starter-logging-2.3.4.RELEASE.jar;C:UsersAdmin.m2repositorychqoslogbacklogback-classic1.2.3logback-classic-1.2.3.jar;C:UsersAdmin.m2repositorychqoslogbacklogback-core1.2.3logback-core-1.2.3.jar;C:UsersAdmin.m2repositoryorgapachelogginglog4jlog4j-to-slf4j2.13.3log4j-to-slf4j-2.13.3.jar;C:UsersAdmin.m2repositoryorgapachelogginglog4jlog4j-api2.13.3log4j-api-2.13.3.jar;C:UsersAdmin.m2repositoryorgslf4jjul-to-slf4j1.7.30jul-to-slf4j-1.7.30.jar;C:UsersAdmin.m2repositoryjakartaannotationjakarta.annotation-api1.3.5jakarta.annotation-api-1.3.5.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-core5.2.9.RELEASEspring-core-5.2.9.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-jcl5.2.9.RELEASEspring-jcl-5.2.9.RELEASE.jar;C:UsersAdmin.m2repositoryorgyamlsnakeyaml1.26snakeyaml-1.26.jar;C:UsersAdmin.m2repositoryorgprojectlomboklombok1.18.12lombok-1.18.12.jar;C:UsersAdmin.m2repositoryorgslf4jslf4j-api1.7.30slf4j-api-1.7.30.jar" com.zhiguo.EchoClientApplication

  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _    
( ( )___ | '_ | '_| | '_ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |___, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.4.RELEASE)

2021-10-12 10:23:23.485  INFO 14240 --- [           main] com.zhiguo.EchoClientApplication         : Starting EchoClientApplication on PS-12 with PID 14240 (D:giteenetty-starterecho-clienttargetclasses started by Admin in D:giteenetty-starter)
2021-10-12 10:23:23.487  INFO 14240 --- [           main] com.zhiguo.EchoClientApplication         : No active profile set, falling back to default profiles: default
2021-10-12 10:23:23.885  INFO 14240 --- [           main] com.zhiguo.EchoClientApplication         : Started EchoClientApplication in 0.736 seconds (JVM running for 1.413)
客户端链接远端:127.0.0.1:8008
EchoClient read:hello

最后

以上就是着急秋天为你收集整理的手写最简版Netty的全部内容,希望文章能够帮你解决手写最简版Netty所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部