1

Current Situation

  • On the linux server several jars are running with sockets - listening and responding with string messages
  • A new war running in an wildfly application server is delegating requests to these sockets
  • The WAR is using spring and especially spring integration with annotations

I have a configuration class holding the services @Configuration / @EnableIntegration /@IntegrationComponentScan

I've created a messaging gateway

@MessagingGateway(defaultRequestChannel = "testGateway")
public interface TestGateway{
    public Future<String> sendMessage(String in);
}

The application should sending requests and receiving it as a client. I've created a null event handler since the application should just send the string and wait for the answer

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

@Bean
@ServiceActivator(inputChannel = "testGateway")
public MessageHandler testGate() {
    final TcpOutboundGateway gate = new TcpOutboundGateway();
    gate.setConnectionFactory(connectionFactory());
    gate.setReplyChannel(docServerChannel());
    return gate;
}

@Bean
public AbstractClientConnectionFactory connectionFactory() {
    final AbstractClientConnectionFactory connectionFactory = new TcpNetClientConnectionFactory("localhost", 5959);
    connectionFactory.setSoTimeout(300000);
    connectionFactory.setApplicationEventPublisher(new NullEventPublisher());
    connectionFactory.setSerializer(new DefaultSerializer());
    connectionFactory.setDeserializer(new DefaultDeserializer());
    return connectionFactory;
}

The messages should be converted to Strings when receiving data and to bytes when sending them

@MessageEndpoint
public static class TestMessage {

    @Transformer(inputChannel = "testChannel")
    public String convert(final byte[] bytes) {
        return new String(bytes);
    }

    @Transformer(inputChannel = "testGateway")
    public String convertResult(final byte[] bytes) {
        return new String(bytes);
    }

}

The application is deployed but the response is always timing out. The socket is running. I just want a simple direct bidirectional connection: WAR <-> JAR.

Can someone help or give me a hint?

------UPDATE-1----------

The socket is receiving the message but then response cannot be read beacuse the socket is closed after sending the message.

------UPDATE-2----------

  • It was a typo. The system is return a MessageHandler
  • I've added the factory as a spring managed bean
  • I've added '\r\n' to the legacy code
  • The application is still complaining "Timed out waiting for response"

The legacy server is opening up a server socket and sending messages to socket

final OutputStream os = serverSocket.getOutputStream();
final PrintWriter pw = new PrintWriter(os, true);
final BufferedReader br = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
final String incoming = br.readLine();
final String response= "ok\r\n";
pw.println(response);
pw.flush();
Thread.sleep(5000);
pw.close();
serverSocket.close();

------UPDATE-3----------

The TcpOutboundGateway from Spring is getting no response

        connection.send(requestMessage);
        Message<?> replyMessage = reply.getReply();
        if (replyMessage == null) {

1 Answer 1

3

The connection factory needs to be a @Bean so that Spring can manage it.

public TcpInboundGateway testGate() {
    final AbstractClientConnectionFactory connectionFactory = new TcpNetClientConnectionFactory("localhost", 5959); // already running socket
    connectionFactory.setApplicationEventPublisher(new NullEventPublisher());
    final TcpOutboundGateway gate = new TcpOutboundGateway();
    gate.setConnectionFactory(connectionFactory);
    gate.setOutputChannelName("testChannel");
    return gate;
}

This won't compile; the return type doesn't match what you are returning.

Assuming this is just a typo here and the bean is in fact an outbound gateway, with this configuration, the reply must be terminated with \r\n (CRLF).

See the documentation; scroll down to...

TCP is a streaming protocol; this means that some structure has to be provided to data transported over TCP, so the receiver can demarcate the data into discrete messages. Connection factories are configured to use (de)serializers to convert between the message payload and the bits that are sent over TCP. This is accomplished by providing a deserializer and serializer for inbound and outbound messages respectively. A number of standard (de)serializers are provided.

...and read about the standard deserializers. With your configuration, the standard deserializer is waiting for the terminaing \r\n (CRLF).

What does the server code do?

EDIT

@SpringBootApplication
public class So49046888Application {

    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext ctx = SpringApplication.run(So49046888Application.class, args);
        String reply = ctx.getBean(TestGateway.class).sendMessage("foo").get();
        System.out.println(reply);
        Thread.sleep(10_000);
        ctx.close();
    }

    @Bean
    public ServerSocket serverSocket() throws IOException {
        return ServerSocketFactory.getDefault().createServerSocket(5959);
    }

    @Bean
    public ApplicationRunner runner(TaskExecutor exec) {
        return args -> {
            exec.execute(() -> {
                try {
                    while (true) {
                        Socket socket = serverSocket().accept();
                        final OutputStream os = socket.getOutputStream();
                        final PrintWriter pw = new PrintWriter(os, true);
                        final BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        final String incoming = br.readLine();
                        System.out.println(incoming);
                        final String response= "ok\r\n";
                        pw.print(response);
                        pw.flush();
                        Thread.sleep(5000);
                        pw.close();
                        socket.close();
                    }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            });
        };
    }

    @Bean
    public TaskExecutor exec() {
        return new ThreadPoolTaskExecutor();
    }

    @Bean
    @ServiceActivator(inputChannel = "testGateway")
    public MessageHandler testGate() {
        final TcpOutboundGateway gate = new TcpOutboundGateway();
        gate.setConnectionFactory(connectionFactory());
        gate.setReplyChannelName("toString");
        gate.setRemoteTimeout(60_000);
        return gate;
    }

    @Transformer(inputChannel = "toString")
    public String transform(byte[] bytes) {
        return new String(bytes);
    }

    @Bean
    public AbstractClientConnectionFactory connectionFactory() {
        final AbstractClientConnectionFactory connectionFactory = new TcpNetClientConnectionFactory("localhost", 5959);
        connectionFactory.setSoTimeout(300000);
        return connectionFactory;
    }

    @MessagingGateway(defaultRequestChannel = "testGateway")
    public static interface TestGateway {
        public Future<String> sendMessage(String in);
    }

}
8
  • Edited my question to answer with more Details. Mar 1, 2018 at 14:39
  • I suggest you turn on DEBUG level logging for org.springframework.integration; you'll get lots of info that should help track things down. Mar 1, 2018 at 14:46
  • THe debug mode does nothing new : TcpNetConnectio Read exception localhost:5959:55274:d08b8ffe-f2a9-465f-9165-956db23adbdb SocketException:Socket closed Mar 1, 2018 at 15:04
  • You are now using Java Serialization instead of the default CRLF serialization - I edited my answer with a working example. Mar 1, 2018 at 15:18
  • You should also use pw.print() on the server not println() to avoid an extra \n. If you want to use println, use the ByteArrayLfSerializer and remove the \r\n. Mar 1, 2018 at 15:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.