Netty框架实现TCP/IP通信的完美过程
项目中需要使用到TCP/IP协议完成数据的发送与接收。如果只是用以前写的简单的socket套接字方法,每次接收发送消息都会创建新的socket再关闭socket,造成资源浪费。于是使用netty框架完成java网络通信。
Netty框架的内容很多,这里只是代码展示其中的一个功能。
代码仓库
这里使用的是Springboot+Netty框架,使用maven搭建项目。这里是在一个项目中搭建服务端与客户端,所以端口一样。还可以使用TCP/UTP工具自己搭建服务端和客户端,只要在yml文件中修改ip和端口就好。
pom.xml
4.0.0 com.hzx.testmaven15netty testmaven15netty1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent2.3.0.RELEASE org.springframework.boot spring-boot-starterio.netty netty-all4.1.31.Final
application.yml
server:port: 8080# 作为客户端请求的服务端地址netty:tcp:server:# 作为客户端请求的服务端地址host: 127.0.0.1# 作为客户端请求的服务端端口port: 7000client:# 作为服务端开放给客户端的端口port: 7000
服务端
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; @Componentpublic class NettyTcpServer {private static final Logger LOGGER = LoggerFactory.getLogger(NettyTcpServer.class); // boss事件轮询线程组// 处理Accept连接事件的线程,这里线程数设置为1即可,netty处理链接事件默认为单线程,过度设置反而浪费cpu资源private EventLoopGroup boss = new NioEventLoopGroup(1); //worker事件轮询线程组//处理handler的工作线程,其实也就是处理IO读写 。线程数据默认为 CPU 核心数乘以2private EventLoopGroup worker = new NioEventLoopGroup(); @AutowiredServerChannelInitializer serverChannelInitializer; @Value("${netty.tcp.client.port}")private Integer port; // 与客户端建立连接后得到的通道对象private Channel channel; /*** 存储client的channel* key:ip value:Channel*/public static Map map = new ConcurrentHashMap(); /*** 开启Netty tcp server服务** @return*/public ChannelFuture start() {// 启动类ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(boss, worker)//组配置,初始化ServerBootstrap的线程组.channel(NioServerSocketChannel.class)//构造channel通道工厂 bossGroup的通道,只是负责连接.childHandler(serverChannelInitializer) //设置通道处理者ChannelHandlerWorkerGroup的处理器.option(ChannelOption.SO_BACKLOG, 1024)//socket参数,当服务器请求处理程全满时,用于临时存放已完成三次握手请求的队列的最大长度。如果未设置或所设置的值小于1,Java将使用默认值50。.childOption(ChannelOption.SO_KEEPALIVE, true); //启用心跳保活机制,tcp,默认2小时发一次心跳//Future:异步任务的生命周期,可用来获取任务结果ChannelFuture channelFuture1 = serverBootstrap.bind(port).syncUninterruptibly(); // 绑定端口 开启监听 同步等待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服务*/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; @Componentpublic class ServerChannelInitializer extends ChannelInitializer {@AutowiredServerChannelHandler serverChannelHandler; @Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {ChannelPipeline pipeline = socketChannel.pipeline(); //IdleStateHandler心跳机制,如果超时触发Handle中userEventTrigger()方法pipeline.addLast("idleStateHandler",new IdleStateHandler(15,0,0, TimeUnit.MINUTES)); // 字符串编解码器pipeline.addLast(new StringDecoder(),new StringEncoder()); // 自定义Handlerpipeline.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.Sharablepublic class ServerChannelHandler extends SimpleChannelInboundHandler
客户端
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; @Componentpublic 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; @AutowiredClientChannelInitializer clientChannelInitializer; private Channel channel; /*** 初始化 `Bootstrap` 客户端引导程序* @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); // 心跳报活return bootstrap; }/***建立连接,获取连接通道对象*/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); }}/*** 向服务器发送消息*/public void sendMessage(Object msg) throws InterruptedException {if (channel != null) {channel.writeAndFlush(msg).sync(); }else {LOGGER.warn("消息发送失败,连接尚未建立"); }}}
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; @Componentpublic class ClientChannelInitializer extends ChannelInitializer {@AutowiredClientChannelHandler clientChannelHandler; @Overrideprotected 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.Sharablepublic class ClientChannelHandler extends SimpleChannelInboundHandler
启动类
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; @SpringBootApplicationpublic class StartApplication implements CommandLineRunner {public static void main(String[] args) throws Exception {SpringApplication.run(StartApplication.class, args); }@AutowiredNettyTcpServer nettyTcpServer; @AutowiredNettyTcpClient nettyTcpClient; /*** Callback used to run the bean.** @param args incoming main method arguments* @throws Exception on error*/@Overridepublic 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(); }}
使用循环让客户端向服务端发送10条数据
运行结果
文章图片
"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【Netty框架实现TCP/IP通信的完美过程】到此这篇关于Netty框架实现TCP/IP通信的文章就介绍到这了,更多相关Netty框架实现TCP/IP通信内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
._______ _ _
/\\ / ___'_ __ _ _(_)_ ____ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/___)| |_)| | | | | || (_| |) ) ) )
'|____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot ::(v2.3.0.RELEASE)
2021-07-13 08:32:17.161INFO 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.165INFO 18068 --- [main] com.netty.StartApplication: No active profile set, falling back to default profiles: default
2021-07-13 08:32:18.371INFO 18068 --- [main] com.netty.StartApplication: Started StartApplication in 1.706 seconds (JVM running for 2.672)
2021-07-13 08:32:18.931INFO 18068 --- [main] com.netty.server.NettyTcpServer: Netty tcp server start success,port=7000
2021-07-13 08:32:19.016INFO 18068 --- [main] com.netty.client.NettyTcpClient: connect tcp server host = 127.0.0.1,port = 7000 success
2021-07-13 08:32:19.078INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler: tcp client /127.0.0.1:52653 connect success
2021-07-13 08:32:19.100INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler: Netty tcp server receive message: hello world 0
2021-07-13 08:32:19.100INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler: Netty tcp server receive message: hello world 1
2021-07-13 08:32:19.100INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler: Netty tcp client receive msg :response message hello world 0
2021-07-13 08:32:19.100INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler: Netty tcp server receive message: hello world 2
2021-07-13 08:32:19.100INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler: Netty tcp client receive msg :response message hello world 1
2021-07-13 08:32:19.100INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler: Netty tcp server receive message: hello world 3
2021-07-13 08:32:19.100INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler: Netty tcp client receive msg :response message hello world 2
2021-07-13 08:32:19.100INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler: Netty tcp server receive message: hello world 4
2021-07-13 08:32:19.100INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler: Netty tcp client receive msg :response message hello world 3
2021-07-13 08:32:19.104INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler: Netty tcp server receive message: hello world 5
2021-07-13 08:32:19.104INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler: Netty tcp client receive msg :response message hello world 4
2021-07-13 08:32:19.104INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler: Netty tcp server receive message: hello world 6
2021-07-13 08:32:19.104INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler: Netty tcp client receive msg :response message hello world 5
2021-07-13 08:32:19.104INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler: Netty tcp server receive message: hello world 7
2021-07-13 08:32:19.104INFO 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.104INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler: Netty tcp server receive message: hello world 8
2021-07-13 08:32:19.104INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler: Netty tcp client receive msg :response message hello world 8
2021-07-13 08:32:19.104INFO 18068 --- [ntLoopGroup-3-1] com.netty.server.ServerChannelHandler: Netty tcp server receive message: hello world 9
2021-07-13 08:32:19.104INFO 18068 --- [ntLoopGroup-4-1] com.netty.client.ClientChannelHandler: Netty tcp client receive msg :response message hello world 9
推荐阅读
- android第三方框架(五)ButterKnife
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- MybatisPlus使用queryWrapper如何实现复杂查询
- python学习之|python学习之 实现QQ自动发送消息
- 标签、语法规范、内联框架、超链接、CSS的编写位置、CSS语法、开发工具、块和内联、常用选择器、后代元素选择器、伪类、伪元素。
- 孩子不是实现父母欲望的工具——林哈夫
- opencv|opencv C++模板匹配的简单实现
- Node.js中readline模块实现终端输入
- java中如何实现重建二叉树
- 人脸识别|【人脸识别系列】| 实现自动化妆