溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Netty框架實(shí)現(xiàn)TCP/IP通信的詳細(xì)過程

發(fā)布時(shí)間:2021-07-13 13:37:38 來源:億速云 閱讀:1907 作者:chen 欄目:開發(fā)技術(shù)

這篇文章主要介紹“Netty框架實(shí)現(xiàn)TCP/IP通信的詳細(xì)過程”,在日常操作中,相信很多人在Netty框架實(shí)現(xiàn)TCP/IP通信的詳細(xì)過程問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”Netty框架實(shí)現(xiàn)TCP/IP通信的詳細(xì)過程”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

      項(xiàng)目中需要使用到TCP/IP協(xié)議完成數(shù)據(jù)的發(fā)送與接收。如果只是用以前寫的簡(jiǎn)單的socket套接字方法,每次接收發(fā)送消息都會(huì)創(chuàng)建新的socket再關(guān)閉socket,造成資源浪費(fèi)。于是使用netty框架完成java網(wǎng)絡(luò)通信。
      Netty框架的內(nèi)容很多,這里只是代碼展示其中的一個(gè)功能。

代碼倉庫

      這里使用的是Springboot+Netty框架,使用maven搭建項(xiàng)目。這里是在一個(gè)項(xiàng)目中搭建服務(wù)端與客戶端,所以端口一樣。還可以使用TCP/UTP工具自己搭建服務(wù)端和客戶端,只要在yml文件中修改ip和端口就好。

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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.hzx.testmaven15netty</groupId>
    <artifactId>testmaven15netty</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.31.Final</version>
        </dependency>
    </dependencies>

</project>

application.yml

server:
  port: 8080

# 作為客戶端請(qǐng)求的服務(wù)端地址
netty:
  tcp:
    server:
      # 作為客戶端請(qǐng)求的服務(wù)端地址
      host: 127.0.0.1
      # 作為客戶端請(qǐng)求的服務(wù)端端口
      port: 7000
    client:
      # 作為服務(wù)端開放給客戶端的端口
      port: 7000

服務(wù)端

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class NettyTcpServer {
    private static final Logger LOGGER = LoggerFactory.getLogger(NettyTcpServer.class);

    // boss事件輪詢線程組
    // 處理Accept連接事件的線程,這里線程數(shù)設(shè)置為1即可,netty處理鏈接事件默認(rèn)為單線程,過度設(shè)置反而浪費(fèi)cpu資源
    private EventLoopGroup boss = new NioEventLoopGroup(1);

    //worker事件輪詢線程組
    //處理handler的工作線程,其實(shí)也就是處理IO讀寫 。線程數(shù)據(jù)默認(rèn)為 CPU 核心數(shù)乘以2
    private EventLoopGroup worker = new NioEventLoopGroup();

    @Autowired
    ServerChannelInitializer serverChannelInitializer;

    @Value("${netty.tcp.client.port}")
    private Integer port;

    // 與客戶端建立連接后得到的通道對(duì)象
    private Channel channel;

    /**
     * 存儲(chǔ)client的channel
     * key:ip value:Channel
     */
    public static Map<String, Channel> map = new ConcurrentHashMap<String, Channel>();

    /**
     * 開啟Netty tcp server服務(wù)
     *
     * @return
     */
    public ChannelFuture start() {
        // 啟動(dòng)類
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, worker)//組配置,初始化ServerBootstrap的線程組
                .channel(NioServerSocketChannel.class)//構(gòu)造channel通道工廠 bossGroup的通道,只是負(fù)責(zé)連接
                .childHandler(serverChannelInitializer) //設(shè)置通道處理者ChannelHandlerWorkerGroup的處理器
                .option(ChannelOption.SO_BACKLOG, 1024)//socket參數(shù),當(dāng)服務(wù)器請(qǐng)求處理程全滿時(shí),用于臨時(shí)存放已完成三次握手請(qǐng)求的隊(duì)列的最大長度。如果未設(shè)置或所設(shè)置的值小于1,Java將使用默認(rèn)值50。
                .childOption(ChannelOption.SO_KEEPALIVE, true);//啟用心跳?;顧C(jī)制,tcp,默認(rèn)2小時(shí)發(fā)一次心跳
        //Future:異步任務(wù)的生命周期,可用來獲取任務(wù)結(jié)果
        ChannelFuture channelFuture1 = serverBootstrap.bind(port).syncUninterruptibly(); // 綁定端口 開啟監(jiān)聽 同步等待
        if (channelFuture1 != null && channelFuture1.isSuccess()) {
            channel = channelFuture1.channel();// 獲取通道
            LOGGER.info("Netty tcp server start success,port={}",port);
        }else {
            LOGGER.error("Netty tcp server start fail");
        }
        return channelFuture1;
    }

    /**
     * 停止Netty tcp server服務(wù)
     */
    public void destroy(){
        if (channel != null) {
            channel.close();
        }
        try {
            Future<?> future = worker.shutdownGracefully().await();
            if (!future.isSuccess()) {
                LOGGER.error("netty tcp workerGroup shutdown fail,{}",future.cause());
            }
        } catch (InterruptedException e) {
            LOGGER.error(e.toString());
        }
        LOGGER.info("Netty tcp server shutdown success");
    }
}
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    ServerChannelHandler serverChannelHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //IdleStateHandler心跳機(jī)制,如果超時(shí)觸發(fā)Handle中userEventTrigger()方法
        pipeline.addLast("idleStateHandler",
                new IdleStateHandler(15,0,0, TimeUnit.MINUTES));
        // 字符串編解碼器
        pipeline.addLast(
                new StringDecoder(),
                new StringEncoder()
        );
        // 自定義Handler
        pipeline.addLast("serverChannelHandler",serverChannelHandler);
    }
}
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@ChannelHandler.Sharable
public class ServerChannelHandler extends SimpleChannelInboundHandler<Object> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerChannelHandler.class);
    /**
     * 拿到傳過來的msg數(shù)據(jù),開始處理
     * @param channelHandlerContext
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        LOGGER.info("Netty tcp server receive message: {}",msg);
        channelHandlerContext.writeAndFlush(" response message "+msg).syncUninterruptibly();
    }

    /**
     * 活躍的、有效的通道
     * 第一次連接成功后進(jìn)入的方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        LOGGER.info("tcp client "+getRemoteAddress(ctx)+" connect success");
        NettyTcpServer.map.put(getIPString(ctx),ctx.channel());
    }

    /**
     * 不活動(dòng)的通道
     * 連接丟失后執(zhí)行的方法(client端可據(jù)此實(shí)現(xiàn)斷線重連)
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 刪除Channel Map中失效的Client
        NettyTcpServer.map.remove(getIPString(ctx));
        ctx.close();
    }

    /**
     * 異常處理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        // 發(fā)生異常 關(guān)閉連接
        LOGGER.error("引擎{}的通道發(fā)生異常,斷開連接",getRemoteAddress(ctx));
        ctx.close();
    }

    /**
     * 心跳機(jī)制 超時(shí)處理
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        String socketString = ctx.channel().remoteAddress().toString();
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state()== IdleState.READER_IDLE) {
                LOGGER.info("Client: "+socketString+" READER_IDLE讀超時(shí)");
                ctx.disconnect();
            }else if (event.state()==IdleState.WRITER_IDLE){
                LOGGER.info("Client: "+socketString+" WRITER_IDLE寫超時(shí)");
                ctx.disconnect();
            }else if (event.state()==IdleState.ALL_IDLE){
                LOGGER.info("Client: "+socketString+" ALL_IDLE總超時(shí)");
                ctx.disconnect();
            }
        }
    }

    /**
     * 獲取client對(duì)象:ip+port
     * @param channelHandlerContext
     * @return
     */
    public String getRemoteAddress(ChannelHandlerContext channelHandlerContext){
        String socketString = "";
        socketString = channelHandlerContext.channel().remoteAddress().toString();
        return socketString;
    }

    /**
     * 獲取client的ip
     * @param channelHandlerContext
     * @return
     */
    public String getIPString(ChannelHandlerContext channelHandlerContext){
        String ipString = "";
        String socketString = channelHandlerContext.channel().remoteAddress().toString();
        int colonAt = socketString.indexOf(":");
        ipString = socketString.substring(1,colonAt);
        return ipString;
    }
}

客戶端

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.xml.ws.Holder;

@Component
public class NettyTcpClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(NettyTcpClient.class);

    @Value("${netty.tcp.server.host}")
    String HOST;

    @Value("${netty.tcp.server.port}")
    int PORT;

    @Autowired
    ClientChannelInitializer clientChannelInitializer;

    private Channel channel;

    /**
     * 初始化 `Bootstrap` 客戶端引導(dǎo)程序
     * @return
     */
    private final Bootstrap getBootstrap(){
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)//通道連接者
                .handler(clientChannelInitializer)//通道處理者
                .option(ChannelOption.SO_KEEPALIVE,true);// 心跳報(bào)活
        return bootstrap;
    }

    /**
     *  建立連接,獲取連接通道對(duì)象
     */
    public void connect(){
        ChannelFuture channelFuture = getBootstrap().connect(HOST, PORT).syncUninterruptibly();
        if (channelFuture != null&&channelFuture.isSuccess()) {
            channel = channelFuture.channel();
            LOGGER.info("connect tcp server host = {},port = {} success", HOST,PORT);
        }else {
            LOGGER.error("connect tcp server host = {},port = {} fail",HOST,PORT);
        }
    }

    /**
     * 向服務(wù)器發(fā)送消息
     */
    public void sendMessage(Object msg) throws InterruptedException {
        if (channel != null) {
            channel.writeAndFlush(msg).sync();
        }else {
            LOGGER.warn("消息發(fā)送失敗,連接尚未建立");
        }
    }
}
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    ClientChannelHandler clientChannelHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast("idleStateHandler",
                new IdleStateHandler(15,0,0, TimeUnit.MINUTES));
        pipeline.addLast(new StringDecoder(),new StringEncoder());
        pipeline.addLast("clientChannelHandler",clientChannelHandler);
    }
}
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@ChannelHandler.Sharable
public class ClientChannelHandler extends SimpleChannelInboundHandler<Object> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ClientChannelHandler.class);
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        LOGGER.info("Netty tcp client receive msg : " + msg);
    }

}

啟動(dòng)類

import com.netty.client.NettyTcpClient;
import com.netty.server.NettyTcpServer;
import io.netty.channel.ChannelFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class StartApplication implements CommandLineRunner {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(StartApplication.class, args);
    }

    @Autowired
    NettyTcpServer nettyTcpServer;

    @Autowired
    NettyTcpClient nettyTcpClient;

    /**
     * Callback used to run the bean.
     *
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(String... args) throws Exception {
        ChannelFuture start = nettyTcpServer.start();
        nettyTcpClient.connect();
        for (int i = 0; i < 10; i++) {
            nettyTcpClient.sendMessage("hello world "+i);
        }
        start.channel().closeFuture().syncUninterruptibly();
    }
}

使用循環(huán)讓客戶端向服務(wù)端發(fā)送10條數(shù)據(jù)

運(yùn)行結(jié)果

Netty框架實(shí)現(xiàn)TCP/IP通信的詳細(xì)過程

"C:\Program Files\Java\jdk1.8.0_271\bin\java.exe" -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-javaagent:D:\IDEA\IntelliJ IDEA 2019.1.1\lib\idea_rt.jar=62789:D:\IDEA\IntelliJ IDEA 2019.1.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_271\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\sqljdbc4-4.0.0.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\rt.jar;D:\Java Code\testmaven15netty\target\classes;D:\Maven\myreprository\org\springframework\boot\spring-boot-starter\2.3.0.RELEASE\spring-boot-starter-2.3.0.RELEASE.jar;D:\Maven\myreprository\org\springframework\boot\spring-boot\2.3.0.RELEASE\spring-boot-2.3.0.RELEASE.jar;D:\Maven\myreprository\org\springframework\spring-context\5.2.6.RELEASE\spring-context-5.2.6.RELEASE.jar;D:\Maven\myreprository\org\springframework\spring-aop\5.2.6.RELEASE\spring-aop-5.2.6.RELEASE.jar;D:\Maven\myreprository\org\springframework\spring-beans\5.2.6.RELEASE\spring-beans-5.2.6.RELEASE.jar;D:\Maven\myreprository\org\springframework\spring-expression\5.2.6.RELEASE\spring-expression-5.2.6.RELEASE.jar;D:\Maven\myreprository\org\springframework\boot\spring-boot-autoconfigure\2.3.0.RELEASE\spring-boot-autoconfigure-2.3.0.RELEASE.jar;D:\Maven\myreprository\org\springframework\boot\spring-boot-starter-logging\2.3.0.RELEASE\spring-boot-starter-logging-2.3.0.RELEASE.jar;D:\Maven\myreprository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;D:\Maven\myreprository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;D:\Maven\myreprository\org\slf4j\slf4j-api\1.7.30\slf4j-api-1.7.30.jar;D:\Maven\myreprository\org\apache\logging\log4j\log4j-to-slf4j\2.13.2\log4j-to-slf4j-2.13.2.jar;D:\Maven\myreprository\org\apache\logging\log4j\log4j-api\2.13.2\log4j-api-2.13.2.jar;D:\Maven\myreprository\org\slf4j\jul-to-slf4j\1.7.30\jul-to-slf4j-1.7.30.jar;D:\Maven\myreprository\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;D:\Maven\myreprository\org\springframework\spring-core\5.2.6.RELEASE\spring-core-5.2.6.RELEASE.jar;D:\Maven\myreprository\org\springframework\spring-jcl\5.2.6.RELEASE\spring-jcl-5.2.6.RELEASE.jar;D:\Maven\myreprository\org\yaml\snakeyaml\1.26\snakeyaml-1.26.jar;D:\Maven\myreprository\io\netty\netty-all\4.1.31.Final\netty-all-4.1.31.Final.jar" com.netty.StartApplication

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

2021-07-13 08:32:17.161  INFO 18068 --- [           main] com.netty.StartApplication               : Starting StartApplication on LAPTOP-H9JFQJGF with PID 18068 (D:\Java Code\testmaven15netty\target\classes started by huangzixiao in D:\Java Code\testmaven15netty)
2021-07-13 08:32:17.165  INFO 18068 --- [           main] com.netty.StartApplication               : No active profile set, falling back to default profiles: default
2021-07-13 08:32:18.371  INFO 18068 --- [           main] com.netty.StartApplication               : Started StartApplication in 1.706 seconds (JVM running for 2.672)
2021-07-13 08:32:18.931  INFO 18068 --- [           main] com.netty.server.NettyTcpServer          : Netty tcp server start success,port=7000
2021-07-13 08:32:19.016  INFO 18068 --- [           main] com.netty.client.NettyTcpClient          : connect tcp server host = 127.0.0.1,port = 7000 success
2021-07-13 08:32:19.078  INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler    : tcp client /127.0.0.1:52653 connect success
2021-07-13 08:32:19.100  INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler    : Netty tcp server receive message: hello world 0
2021-07-13 08:32:19.100  INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler    : Netty tcp server receive message: hello world 1
2021-07-13 08:32:19.100  INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler    : Netty tcp client receive msg :  response message hello world 0
2021-07-13 08:32:19.100  INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler    : Netty tcp server receive message: hello world 2
2021-07-13 08:32:19.100  INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler    : Netty tcp client receive msg :  response message hello world 1
2021-07-13 08:32:19.100  INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler    : Netty tcp server receive message: hello world 3
2021-07-13 08:32:19.100  INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler    : Netty tcp client receive msg :  response message hello world 2
2021-07-13 08:32:19.100  INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler    : Netty tcp server receive message: hello world 4
2021-07-13 08:32:19.100  INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler    : Netty tcp client receive msg :  response message hello world 3
2021-07-13 08:32:19.104  INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler    : Netty tcp server receive message: hello world 5
2021-07-13 08:32:19.104  INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler    : Netty tcp client receive msg :  response message hello world 4
2021-07-13 08:32:19.104  INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler    : Netty tcp server receive message: hello world 6
2021-07-13 08:32:19.104  INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler    : Netty tcp client receive msg :  response message hello world 5
2021-07-13 08:32:19.104  INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler    : Netty tcp server receive message: hello world 7
2021-07-13 08:32:19.104  INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler    : Netty tcp client receive msg :  response message hello world 6 response message hello world 7
2021-07-13 08:32:19.104  INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler    : Netty tcp server receive message: hello world 8
2021-07-13 08:32:19.104  INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler    : Netty tcp client receive msg :  response message hello world 8
2021-07-13 08:32:19.104  INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler    : Netty tcp server receive message: hello world 9
2021-07-13 08:32:19.104  INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler    : Netty tcp client receive msg :  response message hello world 9

到此,關(guān)于“Netty框架實(shí)現(xiàn)TCP/IP通信的詳細(xì)過程”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI