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