TCP 连接拦截器

您可以为连接工厂配置一个 TcpConnectionInterceptorFactoryChain 的引用。 您可以使用拦截器为连接添加行为,例如协商、安全性及其他选项。 框架目前没有提供拦截器,但请参阅 InterceptedSharedConnectionTests 在源仓库中 获取示例。

测试用例中使用的 HelloWorldInterceptor 工作方式如下:

拦截器首先使用客户端连接工厂进行配置。 当第一个消息通过被拦截的连接发送时,拦截器通过连接发送“Hello”并期望收到“world!”。 当这种情况发生时,协商完成,原始消息被发送。 此外,使用相同连接的后续消息将无需任何额外协商即可发送。

当配置有服务器连接工厂时,拦截器要求第一个消息是“Hello”,如果是,则返回“world!”。 否则,它会抛出异常,导致连接关闭。

所有 TcpConnection 方法都被拦截。 拦截器实例由拦截器工厂为每个连接创建。 如果拦截器是有状态的,工厂应该为每个连接创建一个新实例。 如果无状态,同一个拦截器可以包装每个连接。 拦截器工厂被添加到拦截器工厂链的配置中,您可以通过设置 interceptor-factory 属性将其提供给连接工厂。 拦截器必须扩展 TcpConnectionInterceptorSupport。 工厂必须实现 TcpConnectionInterceptorFactory 接口。 TcpConnectionInterceptorSupport 具有直通方法。 通过扩展此类别,您只需实现您希望拦截的方法。

以下示例展示了如何配置连接拦截器工厂链:

<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"/>