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