如果每次连接到远程服务器时创建(新)引导程序,我都不知道是否存在性能问题。所以我想使用一个单独的bootstrap实例连接到多个服务器。我的代码如下:
Bootstrap b = new Bootstrap();
b.group(new NioEventLoopGroup()).handler(new TestHandler()).channel(NioSocketChannel.class)
.option(ChannelOption.AUTO_READ, false);
ChannelFutureListener listener = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
// connection complete start to read first data
System.out.println("connection established + channel: " + future.channel());
} else {
// Close the connection if the connection attempt has failed.
System.out.println("connection failed");
}
}
};
String[] urls = { "www.google.com", "www.stackoverflow.com", "www.yahoo.com" };
for (String s : urls) {
b = b.clone();
b.remoteAddress(s, 80);
b.connect().addListener(listener);
}
System.in.read();
不幸的是,它崩溃了:
connection established + channel: [id: 0x5df86eec, /192.168.126.136:60414 => www.google.com/173.194.127.209:80]
Exception in thread "main" java.lang.IllegalStateException: channel not registered to an event loop
at io.netty.channel.AbstractChannel.eventLoop(AbstractChannel.java:107)
at io.netty.channel.nio.AbstractNioChannel.eventLoop(AbstractNioChannel.java:102)
at io.netty.channel.nio.AbstractNioChannel.eventLoop(AbstractNioChannel.java:41)
at io.netty.channel.CompleteChannelFuture.executor(CompleteChannelFuture.java:48)
at io.netty.util.concurrent.CompleteFuture.addListener(CompleteFuture.java:49)
at io.netty.channel.CompleteChannelFuture.addListener(CompleteChannelFuture.java:56)
at Test3.main(Test3.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
我认为我以错误的方式使用bootstrap。如果是这样,我每次都应该创建一个全新的bootstrap吗?
至少,我应该使用相同的NioEventLoopGroup,对吗?
答案 0 :(得分:0)
好吧,这是我的错,我忘记添加一个ChannelInitializer。将其更改为以下代码:
b.group(new NioEventLoopGroup()).handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new TestHandler());
}
})