为什么依赖Netty的程序,一运行出现很多本机P环回,很多处于ESTABLISHED状态的TCP连接

下载了个netty 4.1.48版本,运行里面自带的一个http server的样例,想看看网络情况,一打开看到那么多的本地IP环回,我看了其它程序最多也就两个左右,为什么netty那么多?这算是TCP连接吗?自已连自己通信??我一连好几个问号。

上图

在命令符下用 netstat -an -p tcp -b

对应的就是这样的。

后来查阅了很多资料都没找到原因,今天无意中,看到一篇文章,心中疑团顿时释然

原文地址:https://blog.csdn.net/haoel/article/details/2224055

大致意思:

Windows下,Selector.open()会自己和自己建立两条TCP链接。不但消耗了两个TCP连接和端口,同时也消耗了文件描述符。

Linux下,Selector.open()会自己和自己建两条管道。同样消耗了两个系统的文件描述符。

看来netty使用了好多的Selecter.open()

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在Spring Boot中使用Netty连接多个TCP服务端可以通过以下步骤实现: 1. 首先,确保你已经在Spring Boot项目中引入了Netty依赖。可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.65.Final</version> </dependency> ``` 2. 创建一个Netty客户端的处理器类,用于处理接收到的消息。可以继承`SimpleChannelInboundHandler`类,并重写`channelRead0`方法来处理接收到的消息。 ```java public class NettyClientHandler extends SimpleChannelInboundHandler<String> { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { // 处理接收到的消息 System.out.println("Received message: " + msg); } } ``` 3. 创建一个Netty客户端的启动类,用于配置和启动Netty客户端。 ```java @Configuration public class NettyClientConfig { @Value("${netty.server.host}") private String serverHost; @Value("${netty.server.port}") private int serverPort; @Bean public EventLoopGroup eventLoopGroup() { return new NioEventLoopGroup(); } @Bean public Bootstrap bootstrap(EventLoopGroup eventLoopGroup, NettyClientHandler nettyClientHandler) { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new StringEncoder()); pipeline.addLast(new StringDecoder()); pipeline.addLast(nettyClientHandler); } }); return bootstrap; } @Bean public ChannelFuture channelFuture(Bootstrap bootstrap) throws InterruptedException { return bootstrap.connect(serverHost, serverPort).sync(); } } ``` 4. 在配置文件中配置要连接的多个TCP服务端的主机和端口。 ```properties # application.properties netty.server.host=127.0.0.1 netty.server.port=8080 ``` 5. 在需要使用Netty客户端的地方注入`ChannelFuture`对象,并使用它来发送消息给服务端。 ```java @Service public class NettyClientService { @Autowired private ChannelFuture channelFuture; public void sendMessage(String message) { if (channelFuture.channel().isActive()) { channelFuture.channel().writeAndFlush(message); } else { // 连接未建立或已断开,处理相应逻辑 } } } ``` 这样,你就可以在Spring Boot项目中使用Netty连接多个TCP服务端了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值