2014-10-28 49 views
1

有谁知道使用Spring的tcp入站通道适配器CLIENT示例的简单示例?我想创建一个简单的TCP客户端,它向服务器发送一个简短的字符串,并且只接收一个字节作为答案,然后关闭套接字。这里是我的bean定义:是否有任何弹簧集成tcp入站通道适配器的例子?

<int-ip:tcp-connection-factory id="client2" type="client" 
    host="localhost" port="${availableServerSocket}" single-use="true" 
    so-timeout="10000" deserializer="climaxDeserializer" 
    so-keep-alive="false" /> 

<int:service-activator input-channel="clientBytes2StringChannel" 
    method="valaszjott" ref="echoService"> 
</int:service-activator> 

<int:gateway 
    service-interface="org.springframework.integration.samples.tcpclientserver.SimpleGateway" 
    id="gw2" default-request-channel="gwchannel"> 
</int:gateway> 
<int:channel id="gwchannel"></int:channel> 
<int:object-to-string-transformer input-channel="gwchannel" 
    id="clientbyte2string" output-channel="outputchannel"> 
</int:object-to-string-transformer> 
<int:channel id="outputchannel"></int:channel> 
<int-ip:tcp-outbound-channel-adapter channel="outputchannel" 
    id="clientoutboundadapter" connection-factory="client2"> 
</int-ip:tcp-outbound-channel-adapter> 
<int-ip:tcp-inbound-channel-adapter id="clientinboundadapter" 
    channel="inputchannel" connection-factory="client2" /> 
<int:channel id="inputchannel"></int:channel> 
<int:service-activator ref="echoService" method="valaszjott" 
    input-channel="inputchannel" id="sa2"> 
</int:service-activator> 

所以,我用这种方式,从我的主要方法:

.... 
SimpleGateway gateway = (SimpleGateway) context.getBean("gw2"); 
String result = gateway.send("foo"); 
.... 

并须指出的是,客户端发送"foo" + /r/n到服务器。在服务器端,我收到了这条消息,服务器回答客户端只有一个字节,(06H)没有/r/n。客户端收到它,解串器找到它。这里是我的解串器类:

@Component("climaxDeserializer")public class ClimaxDeserializer implements 
Deserializer<Integer>{ 
    public Integer deserialize(InputStream arg0) throws IOException { 
     int ertek; 
     do{ 
      ertek = arg0.read(); 
      if (ertek == 6){ 
       System.out.println("We have the ack byte !"); 
       return 1; 
      } 
     } while(ertek >= 0); 
     return null; 
    } 
} 

的解串器发现ACK字节,并且该方法返回一个整数,值为1 服务激活点,这个方法:

public String valaszjott (int success){ 
     System.out.println("Answer: " + success); 
     if (success == 1){ 
      return "OK"; 
     } else { 
      return "NOK"; 
     } 
    } 

在这指出每一件事情都很好,并且valaszjott方法打印出Answer: 1。但是,结果参数(在main方法中)永远不会得到OKNOK字符串值,并且套接字将保持打开状态。

我在哪里犯了一个错误?如果我改变了tcp-inbound-channel-adaptertcp-outbound-channel-adapter对来tcp-outbound-gateway它工作正常...

回答

1

你的错误在multi-threading规定。

​​调用存在于一个Thread中,但<int-ip:tcp-inbound-channel-adapter>是一个message-driven组件,它是它自己的Thread中的套接字的侦听器。对于最后一个,无关紧要,如果您调用网关或服务器端始终可以将数据包发送到该套接字,并且您的适配器将接收它们。

对于您的ack用例,<tcp-outbound-gateway>是最好的解决方案,因为在请求和回复之间确实有correlation。并让您获得多个并发请求的收益。

只要<tcp-outbound-channel-adapter><tcp-inbound-channel-adapter>不能保证答复将从服务器以与发送请求相同的顺序返回。

无论如何,在您当前的解决方案中,gateway只是不知道回复,最后一个不能从请求消息头传递到replyChannel

从其他侧插座不会被关闭,因为他们是中的cached

HTH

+0

我感谢您的帮助! – 2014-10-29 21:25:51

相关问题