2014-10-28 90 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

相關問題