TCP 連線攔截器

你可以透過引用 TcpConnectionInterceptorFactoryChain 來配置連線工廠。你可以使用攔截器向連線新增行為,例如協商、安全和其他選項。目前框架沒有提供攔截器,但可以在原始碼庫中檢視 InterceptedSharedConnectionTests 以獲取示例

測試用例中使用的 HelloWorldInterceptor 工作方式如下

攔截器首先配置一個客戶端連線工廠。當第一個訊息透過被攔截的連線傳送時,攔截器會透過連線傳送 'Hello' 並期望接收到 'world!'。發生這種情況時,協商完成,然後傳送原始訊息。此外,使用相同連線的訊息不會進行額外的協商就被髮送出去。

當配置了伺服器連線工廠時,攔截器要求第一個訊息是 'Hello',如果是,則返回 'world!'。否則,它會丟擲一個異常,導致連線關閉。

所有的 TcpConnection 方法都會被攔截。攔截器例項由攔截器工廠為每個連線建立。如果攔截器是有狀態的,工廠應該為每個連線建立一個新例項。如果它沒有狀態,同一個攔截器可以包裝每個連線。攔截器工廠被新增到攔截器工廠鏈的配置中,你可以透過設定 interceptor-factory 屬性將其提供給連線工廠。攔截器必須繼承 TcpConnectionInterceptorSupport。工廠必須實現 TcpConnectionInterceptorFactory 介面。TcpConnectionInterceptorSupport 有透傳(passthrough)方法。透過繼承這個類,你只需要實現你想攔截的方法。

以下示例展示瞭如何配置連線攔截器工廠鏈

<bean id="helloWorldInterceptorFactory"
    class="o.s.i.ip.tcp.connection.TcpConnectionInterceptorFactoryChain">
    <property name="interceptors">
        <array>
            <bean class="o.s.i.ip.tcp.connection.HelloWorldInterceptorFactory"/>
        </array>
    </property>
</bean>

<int-ip:tcp-connection-factory id="server"
    type="server"
    port="12345"
    using-nio="true"
    single-use="true"
    interceptor-factory-chain="helloWorldInterceptorFactory"/>

<int-ip:tcp-connection-factory id="client"
    type="client"
    host="localhost"
    port="12345"
    single-use="true"
    so-timeout="100000"
    using-nio="true"
    interceptor-factory-chain="helloWorldInterceptorFactory"/>