membersound
membersound

Reputation: 86627

How to use the same MessageChannel for both send and receive in Spring-Integration?

I'm creating a client that connects to a server socket. The server replies directly and closes the socket itself.

The following code works in general. Means: I can see the output printed to console.

@Service
public class MyService {
    @Autowired
    @Qualifier("clientChannel")
    private MessageChannel clientChannel;

    public void send() {
        Message<?> msg = MessageBuilder.withPayload("test\n").build();
        Message<?> rsp = new MessagingTemplate(clientChannel).sendAndReceive(msg);
    }
}


@Component
public class MyConfig {
    @Bean
    public AbstractClientConnectionFactory clientFactory() throws Exception {
        TcpConnectionFactoryFactoryBean f = new TcpConnectionFactoryFactoryBean();
        f.setType("client");
        f.setHost(host);
        f.setPort(port);
        f.setUsingNio(true);
        f.setSingleUse(true);
        f.setSoTimeout(timeout);
        f.setDeserializer(new ByteArrayRawSerializer());
        return fact;
    }

    @Bean
    @ServiceActivator(inputChannel = "clientChannel")
    public TcpOutboundGateway outGateway(AbstractClientConnectionFactory factory,
        @Qualifier("replayChannel") MessageChannel chan) throws Exception {
        TcpOutboundGateway g = new TcpOutboundGateway();
        g.setConnectionFactory(factory);
        g.setReplyChannel(chan);
        return g;
    }


    @ServiceActivator(inputChannel = "replyChannel")
    public void replyHandler(byte[] in) {
        System.out.println("replyHandler:"+new String(in));
    }

    @Bean
    public MessageChannel clientChannel() {
        return new DirectChannel();
    }

    @Bean
    public MessageChannel replyChannel() {
        return new DirectChannel();
    }
}

Problem: I'd like to drop the replyChannel and use the clientChannel to receive the response by msg.sendAndReceive().

@Bean
@ServiceActivator(inputChannel = "clientChannel")
public TcpOutboundGateway outGateway(AbstractClientConnectionFactory factory,
    @Qualifier("clientChannel") MessageChannel chan) throws Exception {
    TcpOutboundGateway g = new TcpOutboundGateway();
    g.setConnectionFactory(factory);
    g.setReplyChannel(chan);
    return g;
}

But that won't work. The execution hangs forever inside the TcpOutboundGateway and never returns. But WHY?

In debug mode I can see that the following is printed over and over again:

DEBUG o.s.i.i.t.TcpOutboundGateway: second chance This is not printed if I use the replyChannel that I want to get rid of.

Upvotes: 0

Views: 385

Answers (1)

membersound
membersound

Reputation: 86627

To answer my own question: Omit the g.setReplyChannel(chan); completely. Then the gateway will just send the output back to the message template by default.

Upvotes: 1

Related Questions