2017-03-08 94 views
3

我想设置Spring TCP Server-Client应用程序。我需要一个服务器监听端口上的传入消息,例如6666,并且客户端在不同的端口上发送消息,例如7777.我遵循documentation,但我坚持客户期望的问题收到回复,但实际上,另一端只会收到来自客户端的消息,不会发送任何回应。所以,基本上,我不断收到此错误:Spring Integration TCP

o.s.i.ip.tcp.TcpOutboundGateway   : Tcp Gateway exception 

org.springframework.integration.MessageTimeoutException: Timed out waiting for response 

我发现this答案类似的问题,所以我想答案在我的代码整合。这是我的配置类:

@EnableIntegration 
@IntegrationComponentScan 
@Configuration 
public class Config { 

private int port = 6666; 

@MessagingGateway(defaultRequestChannel = "toTcp") 
public interface Gateway { 
    String viaTcp(String in); 
} 

@Bean 
@ServiceActivator(inputChannel = "toTcp") 
public TcpOutboundGateway tcpOutGate(AbstractClientConnectionFactory connectionFactory) { 
    TcpOutboundGateway gate = new TcpOutboundGateway(); 
    gate.setConnectionFactory(connectionFactory); 
    gate.setOutputChannelName("resultToString"); 
    gate.setRequiresReply(false); 

    return gate; 
} 

@Bean 
public TcpInboundGateway tcpInGate(AbstractServerConnectionFactory connectionFactory) { 
    TcpInboundGateway inGate = new TcpInboundGateway(); 
    inGate.setConnectionFactory(connectionFactory); 
    inGate.setRequestChannel(fromTcp()); 

    return inGate; 
} 

@Bean 
public ByteArrayRawSerializer serializer() { 
    return new ByteArrayRawSerializer(); 
} 

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

@MessageEndpoint 
public static class Echo { 

    @Transformer(inputChannel = "fromTcp", outputChannel = "toEcho") 
    public String convert(byte[] bytes) { 
     return new String(bytes); 
    } 

    @ServiceActivator(inputChannel = "toEcho") 
    public String upCase(String in) { 
     System.out.println("Server received: " + in); 
     return in.toUpperCase(); 
    } 

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

} 

@Bean 
public AbstractClientConnectionFactory clientCF() { 
    TcpNetClientConnectionFactory tcpNet = new TcpNetClientConnectionFactory("localhost", 7777); 
    tcpNet.setDeserializer(serializer()); 
    tcpNet.setSerializer(serializer()); 
    tcpNet.setSingleUse(true); 
    tcpNet.setTaskExecutor(new NullExecutor()); 
    return tcpNet; 
} 

@Bean 
public AbstractServerConnectionFactory serverCF() { 
    TcpNetServerConnectionFactory tcp = new TcpNetServerConnectionFactory(this.port); 
    tcp.setSerializer(serializer()); 
    tcp.setDeserializer(serializer()); 
    return tcp; 
} 


public class NullExecutor implements Executor { 

    public void execute(Runnable command) {} 
} 

}

这是我如何使用客户端发送消息:

@Autowired 
private Gateway gateway; 
gateway.viaTcp("Some message"); 

我怎样才能安装客户端,因此它不等待为了回应?

回答

4

查看reference manual

网关用于请求/回复交互,通道适配器用于单向交互。

使用TcpSendingMessageHandlerTcpReceivingChannelAdapter而不是入站和出站网关。

相关问题