2014-08-27 108 views
0

我剛開始使用Spring-Integration,並且實現了向服務器發送「OK」消息的TCP服務器。我想記錄客戶端IP地址和從客戶端收到的文本。Spring集成TCP服務器:獲取IP地址和負載

我能夠通過下面的配置文件成功獲取客戶端發送的文本,但我不知道如何獲取客戶端的IP地址。

以下是TCP服務器的配置文件。

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:int="http://www.springframework.org/schema/integration" 
    xmlns:int-ip="http://www.springframework.org/schema/integration/ip" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd 
    http://www.springframework.org/schema/integration/ip http://www.springframework.org/schema/integration/ip/spring-integration-ip.xsd"> 

<context:property-placeholder /> 
<int-ip:tcp-connection-factory id="tcpServer" 
           type="server" 
           using-nio="true" 
           port="${tcpServer.port}"/> 

<int-ip:tcp-inbound-gateway id="tcpGateway" 
          connection-factory="tcpServer" 
          request-channel="bytesChannel" 
          error-channel="errorChannel"/> 


<int:service-activator input-channel="inputChannel" ref="myTcpService" method="processInput"/> 

<bean id="myTcpService" class="MyTcpService" /> 

<int:transformer id="transformerBytes2String" 
       input-channel="bytesChannel" 
       output-channel="inputChannel" 
       expression="new String(payload)"/> 

<int:transformer id="errorHandler" 
       input-channel="errorChannel" 
       expression="payload.failedMessage.payload + ':' + payload.cause.message"/> 

<int:channel id="inputChannel" /> 
<int:channel id="bytesChannel"/> 

</beans> 

MyTcpService類:

public class MyTcpService { 
    public String processInput(String input){ 
     return "OK"; 
    } 
} 

我想知道是否有可能與在「processInput」方法的有效載荷相處的IP地址。

回答

1

幾個連接屬性都存儲在MessageHeadersTcpMessageMapper):

messageBuilder 
     .setHeader(IpHeaders.HOSTNAME, connection.getHostName()) 
     .setHeader(IpHeaders.IP_ADDRESS, connection.getHostAddress()) 
     .setHeader(IpHeaders.REMOTE_PORT, connection.getPort()) 
     .setHeader(IpHeaders.CONNECTION_ID, connectionId); 

因此,你可以簡單的添加一個參數傳送給processInput方法得到所需的標題值:

public String processInput(String input, @Header(IpHeaders.IP_ADDRESS) String ip){ 

當沒有任何註釋的input參數仍然映射到​​。

+0

您也可以用'替換'transformerBytes2String'變壓器' – 2014-08-27 21:27:04