我正在尝试实现一个 tcp 客户端,它将使用 spring 集成连接到现有服务器。由于对这项技术还很陌生,我遵循了 https://github.com/spring-projects/spring-integration-samples 上的 Spring 示例。 .
我已经成功实现了一个简单的情况,即客户端连接到服务器,然后发送请求,然后接收从服务器返回的响应。但是,由于我们服务器的实现方式,我现在需要实现以下情况:客户端必须连接到服务器并等待来自服务器的请求,然后用响应数据进行响应。
我该如何实现这个?看起来我不能再在客户端使用网关,因为网关要求我先发送请求,然后才能获取任何响应数据。然后,我考虑配置一个服务激活器,将 tcp-outbound-gateway 的回复 channel 作为其输入 channel 。但是,服务实现没有收到任何回复。似乎只有在我从客户端发送第一个请求后,该 channel 才会打开。目前我有以下内容:
Spring 配置:
<int-ip:tcp-connection-factory id="client"
type="client"
host="localhost"
port="12345"
single-use="false"
so-timeout="10000"
deserializer="javaSerializerDeserializer"
serializer="javaSerializerDeserializer" />
<bean id="javaSerializerDeserializer"
class="org.springframework.integration.ip.tcp.serializer.ByteArrayLfSerializer" />
<int-ip:tcp-outbound-gateway id="outGateway"
request-channel="input"
reply-channel="clientBytes2StringChannel"
connection-factory="client"
request-timeout="10000"
reply-timeout="10000" />
<int:object-to-string-transformer id="clientBytes2String"
input-channel="clientBytes2StringChannel" />
<int:service-activator input-channel="clientBytes2StringChannel" ref="thinclientService" />
<bean id="thinclientService" class="tcp.service.ThinClientService" />
ThinClientService:
@Component
public class ThinClientService {
private static final Logger LOGGER = LoggerFactory.getLogger(ThinClientService.class);
public String receive(String recv) {
LOGGER.info("*****************Recv: {}", recv);
return "echo";
}
}
主要方法:
@SpringBootApplication
public class Application {
public static void main(String args[]) throws Exception {
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
context.load("classpath:META-INF/beans.xml");
context.registerShutdownHook();
context.refresh();
System.out.println("Running test");
SpringApplication.run(Application.class, args);
}
}
即使我不想发送数据,如何强制该客户端连接到我的服务器?
最佳答案
我自己设法解决了这个问题。我必须将 tcp-outbound-gateway 更改为 client-mode="true"的 tcp-inbound-gateway。只有这样,服务激活器才会收到服务器发送的消息。
更新了 bean 配置:
<int-ip:tcp-connection-factory id="client"
type="client"
host="localhost"
port="12345" single-use="false" so-timeout="10000" deserializer="javaSerializerDeserializer"
serializer="javaSerializerDeserializer" />
<bean id="javaSerializerDeserializer"
class="org.springframework.integration.ip.tcp.serializer.ByteArrayLfSerializer" />
<int-ip:tcp-inbound-gateway id="outGateway"
request-channel="input"
connection-factory="client"
client-mode="true"
retry-interval="1000"
scheduler="reconnectScheduler" />
<bean id="reconnectScheduler" class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler" />
<int:object-to-string-transformer id="clientBytes2String"
input-channel="input" output-channel="responseString" />
<int:service-activator input-channel="responseString" ref="thinclientService" />
<bean id="thinclientService" class="tcp.service.ThinClientService" />
关于java - 使用 Spring 集成从服务器向客户端发送请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36862582/