我试图实现一个tcp客户端,它将使用spring集成连接到现有服务器。作为这项技术的新手,我在https://github.com/spring-projects/spring-integration-samples处遵循了春天的例子。
我设法实现客户端连接到服务器的简单情况,然后发送请求,然后从服务器接收响应。但是,由于我们的服务器的实现方式,我现在需要实现以下情况:客户端必须连接到服务器并等待来自服务器的请求,然后响应响应数据。
我该如何实现?看起来我不能在客户端使用网关,因为网关要求我在获得任何响应数据之前发送请求。然后我考虑使用tcp-outbound-gateway的reply-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);
}
}
即使我不想发送数据,如何强制此客户端连接到我的服务器?
答案 0 :(得分:1)
管理自己解决这个问题。我必须使用client-mode =&#34; true&#34;将tcp-outbound-gateway更改为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" />