Netty 4从客户端创建多个连接
我试图创建多个客户端连接到另一台机器上的基于Java的套接字服务器。 服务器和客户端都使用Netty 4作为NIO。 在服务器端,我使用了boss和worker组,并且它能够在单个linux机器上接收和服务100000个并发连接(在设置内核参数和ulimit之后)。
但是,我最终在客户端的每个连接上创建了一个新线程,并导致JVM线程限制异常。
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class TelnetClient
{
private Bootstrap b;
private NioEventLoopGroup loopGroup;
private TelnetConnectionInitializer tci;
public static void main(String[] args) throws Exception
{
System.out.println("TelnetClient:main:enter " + args[0]);
TelnetClient tc = new TelnetClient();
String countStr = args[0]; //number of connections to make
int count = Integer.valueOf(countStr);
for (int i=0; i < count; i++)
{
params.add(String.valueOf(i));
Runnable r = new ClientThread(tc);
new Thread(r).start();
}
System.out.println("TelnetClient:main:exit");
}
public TelnetClient()
{
System.out.println("TelnetClient:TelnetClient");
b = new Bootstrap();
loopGroup = new NioEventLoopGroup();
b = b.group(loopGroup);
b = b.channel(NioSocketChannel.class);
tci = new TelnetConnectionInitializer();
}
public void connect(String host, int port) throws Exception {
System.out.println("TelnetClient:connect:enter");
try {
b.handler(tci).connect(host, port).sync().channel().closeFuture().sync();
} finally {
b.group().shutdownGracefully();
}
System.out.println("TelnetClient:connect:exit");
}
}
/// Creating a new thread per connection,
/// Which seems the culprit of JVM exception, but couldn't found a way to implement boss / worker like solution on client side.
class ClientThread implements Runnable
{
TelnetClient myTc;
public ClientThread(TelnetClient tc)
{
myTc = tc;
}
public void run()
{
System.out.println("ClientThread:run");
try
{
myTc.connect("192.168.1.65", 4598); //Server running on different machine in local network
} catch (Exception e)
{
e.printStackTrace();
}
}
}
有人可以指出,我可以如何使用Netty从客户端创建多个连接,而不会为每个客户端产生新的线程。 我尝试了在堆栈溢出的另一篇文章中找到类似条件的唯一代码片段,但在那里,对于我自己执行第一次成功连接后暂停(进入无限等待状态)。
谢谢
除了两件重要的事情之外,代码看起来是正确的 - 您必须共享所有客户端的netty上下文并异步工作。
即在开始时初始化EvenetLoopGroup,并将此单个实例传递给每个客户端对Bootstrap.group()的每次调用。
对于异步aproach,避免connect()将来的sync()(不那么重要),主要是close()将来。 后者代码被暂停,直到连接关闭。
链接地址: http://www.djcxy.com/p/95221.html