[英]Spring Integration TCP
我想設置Spring TCP Server-Client應用程序。 我需要一個服務器監聽端口上的傳入消息,例如,6666,以及客戶端在不同的端口上發送消息,例如7777.我已經按照文檔 ,但我遇到了客戶期望的問題收到回復,但事實上,另一端只會收到來自客戶的消息,不會發送任何回復。 所以,基本上,我經常遇到這個錯誤:
o.s.i.ip.tcp.TcpOutboundGateway : Tcp Gateway exception
org.springframework.integration.MessageTimeoutException: Timed out waiting for response
我發現這個答案類似的問題,所以我想答案在我的代碼整合。 這是我的Config類:
@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");
如何設置客戶端以使其不等待響應?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.