2017-10-20 5761 views
0

我开始使用Netty Library并且希望将可以连接到我的服务器的客户端数设置为4,我该怎么办?如何使用netty设置最大并发连接数

感谢

+0

根据这个答案:https://stackoverflow.com/a/19045001/5515060,它不可能 – Lino

+0

好吧...我会尝试其他的东西。谢谢 – Papaya

回答

1

最简单的方法是写自己的处理程序,其对连接的客户端在静态整数。

事情是这样的:

import io.netty.channel.ChannelHandler.Sharable; 
import io.netty.channel.ChannelHandlerContext; 
import io.netty.channel.ChannelInboundHandlerAdapter; 

@Sharable 
public class ConnectionCounter extends ChannelInboundHandlerAdapter { 

    private static int connections = 0; 

    @Override 
    public void channelActive(ChannelHandlerContext ctx) throws Exception { 
     if(connections < 4) { 
      connections++; 
      super.channelActive(ctx); 
     } else 
      ctx.close(); 
    } 

    @Override 
    public void channelInactive(ChannelHandlerContext ctx) throws Exception { 
     super.channelInactive(ctx); 
     connections--; 
    } 
} 

编辑

你应该记住,你必须使用一个线程,否则可能会导致一些问题(竞争状态)。如果必须使用多个线程,则将int更改为AtomicInteger或使用static int中的synchronized关键字。

1

您不能配置netty来限制传入连接的数量。但是,您可以在打开后关闭超出限制的连接。 有几种方法可以实现这一点。

第一个将如上例所示。您需要在流水线开头添加ConnectionCounter处理程序。但是,你需要使用AtomicInteger代替int connections并增加检查前的柜台(以避免竞争状态的问题):

@Sharable 
public class ConnectionCounter extends ChannelInboundHandlerAdapter { 

private final AtomicInteger connections = new AtomicInteger(); 

@Override 
public void channelActive(ChannelHandlerContext ctx) throws Exception { 
    int val = connections.incrementAndGet(); 
    if (val <= 4) { 
     super.channelActive(ctx); 
    } else { 
     ctx.close(); 
    } 
} 

@Override 
public void channelInactive(ChannelHandlerContext ctx) throws Exception { 
    super.channelInactive(ctx); 
    connections.decrementAndGet(); 
} 
} 

P. S.心目中这个处理器是可共享的,你只需要创建1它的实例。否则,您需要使connections字段静态。

另一种选择是使用单线程EventLoop。当你想到只有4个连接 - 他们可以很容易地用1 EventLoop处理:

new ServerBootstrap().group(bossGroup, new EpollEventLoopGroup(1)); 

因此你只有你可以使用上面的ConnectionCounter处理程序代码,但没有AtomicInteger 1个工作者线程。

而最后的选项是 - DefaultChannelGroup。但是,它内部使用ConcurrentMap<ChannelId, Channel>。因此,您可以按照与ConnectionCounter处理程序相同的方式来实现它。