我想设置 Spring TCP 服务器客户端应用程序。我需要一个服务器侦听端口上的传入消息,例如 6666,并且客户端在不同的端口上发送消息,例如 7777。我已遵循文档 http://docs.spring.io/spring-integration/reference/html/ip.html#ip-annotation,但我遇到了这样的问题:客户端期望收到响应,但实际上,另一端只会接收来自客户端的消息,而不会发送任何响应。所以,基本上,我不断收到这个错误:
o.s.i.ip.tcp.TcpOutboundGateway : Tcp Gateway exception
org.springframework.integration.MessageTimeoutException: Timed out waiting for response
I found this https://stackoverflow.com/questions/18974258/write-only-over-a-tcp-connection-with-spring-integration回答类似的问题,所以我尝试将答案集成到我的代码中。这是我的配置类:
@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");
如何设置客户端以便它不等待响应?
See the 参考手册 http://docs.spring.io/spring-integration/reference/html/endpoint-summary.html.
网关用于请求/回复交互,通道适配器用于单向交互。
Use TcpSendingMessageHandler
and TcpReceivingChannelAdapter
而不是入站和出站网关。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)