[英]connect to client in netty in channelhandler
我正在嘗試從我在Netty中構建的服務器連接到另一個客戶端。 我在這里查看了代理示例: http : //netty.io/4.1/xref/io/netty/example/proxy/package-summary.html
因此,在ChannelInboundHandlerAdapter
子類中,我嘗試執行此操作
ctx.pipeline().addLast(new EchoTestHandler("localhost", 3030));
我的EchoTestHandler看起來像:
public class EchoTestHandler extends ChannelInboundHandlerAdapter {
private final String host;
private final int port;
private Channel outboundChannel;
public EchoTestHandler(String host, int port) {
System.out.println("constructor echo test handler");
this.host = host;
this.port = port;
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println("channel test handler");
final Channel inboundChannel = ctx.channel();
// start the connection attempt
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(inboundChannel.eventLoop())
.channel(ctx.channel().getClass())
.handler(new CryptoServerHandler(inboundChannel));
ChannelFuture future = bootstrap.connect(host, port);
outboundChannel = future.channel();
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) {
if (channelFuture.isSuccess()) {
// connection complete, start to read first data
inboundChannel.read();
} else {
// close the connection if connection attempt has failed
inboundChannel.close();
}
}
});
}
}
構造函數將被調用,但是由於尚未連接任何東西, channelActive
無法調用channelActive
。 我也嘗試過,更類似於代理示例:
ctx.pipeline().addLast(new EchoServerInitializer("localhost", 3020));
然后EchoServerInitializer:
public class EchoServerInitializer extends ChannelInitializer<SocketChannel> {
private final String host;
private final int port;
public EchoServerInitializer(String host, int port) {
System.out.println("constructor EchoServerInitializer");
this.host = host;
this.port = port;
}
@Override
public void initChannel(SocketChannel ch) {
System.out.println("EchoServerInitializer initChannel");
ch.pipeline().addLast(
new LoggingHandler(LogLevel.INFO),
new EchoServerHandler()
);
}
}
您需要與代理服務器連接以執行channelActive
調用。 代理示例使用8443
端口,因此您可以使用telnet localhost 8443
命令通過telnet(或其他方式)進行連接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.