如何将收到服务器的消息转发到Netty(Java)中的另一台服务器?

时间:2013-02-18 19:35:22

标签: java jboss connection netty nio

我有一些客户端,他们与一台服务器通信,我需要该服务器将消息转发给另一台服务器。然后,从第二台服务器接收消息并发送给客户端。

使用这种方法,我实现了连接到第二台服务器,但它没有收到消息并抛出以下异常:

EXCEPTION:java.nio.channels.NotYetConnectedException。 java.nio.channels.NotYetConnectedException

public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws IOException, Exception {
        response = "hola" + "\r\n";
        Main.creaLog("Mensaje recibido del conc: " + e.getMessage().toString());
        Main.creaLog("Mensaje enviado al servidor : " + response);


        ClientBootstrap bootstrap1 = new ClientBootstrap(
        new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool()));

        // Configure the pipeline factory.
        //bootstrap1.setPipelineFactory(new CLIENTE.ClientePipelineFactory());
        bootstrap1.setPipelineFactory(new ChannelPipelineFactory() {
         public ChannelPipeline getPipeline() {
                return Channels.pipeline(new ClienteHandler());
         }
        });

        final ChannelFuture future = bootstrap1.connect(new InetSocketAddress("172.16.10.14", 12355));

        Channel channel = future.getChannel();

        if (channel.isWritable()) {
            ChannelFuture lastWriteFuture = channel.write(e.getMessage().toString() + "\r\n");
        }
        close = true;


    // We do not need to write a ChannelBuffer here.
    // We know the encoder inserted at TelnetPipelineFactory will do the conversion.
    ChannelFuture future = e.getChannel().write(response + "\r\n");
    //CIERRA LA CONEXION
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

如果有人能帮助我,我感激不尽。

1 个答案:

答案 0 :(得分:1)

查看Netty Proxy example

现在,您基本上尝试在收到的每条消息上连接到远程服务器。这可能不是你想要的。您可能只想连接到远程服务器一次(即Netty代理示例中的出站通道),并将新的传入消息转发到该特定通道。