有 spring 集成 tcpserver 来管理客户端并向它们发送消息

having spring integration tcpserver to manage clients and send them messages

我已经创建了一个带有 spring 集成的简单 tcp 服务器,它保持连接有效并在连接期间响应每个请求。

在该 requestMethod 中,我还能够读取 MessageHeder 以获取 connectionId。

现在我想从服务器向客户端发送消息。

据我了解文档,我需要将 connectionid 放入 MessageHeader 中,然后发送消息。但我无法弄清楚如何做后一个。我已准备好消息,但我如何 send/push 发送出去?

这是我的 xml- 配置:

<bean id="lfSerializer" class="org.springframework.integration.ip.tcp.serializer.ByteArrayLfSerializer"/>

<int-ip:tcp-connection-factory
    id="socketserver"
    type="server"
    port="30124"
    using-nio="true"
    deserializer="lfSerializer"
    serializer="lfSerializer"
    single-use="false"/>

<int-ip:tcp-inbound-channel-adapter id="inboundServer"
    channel="inputChannel"
    connection-factory="socketserver"/>

<int-ip:tcp-outbound-channel-adapter id="outboundServer"
    channel="outputChannel"
    connection-factory="socketserver"
    />

<int:channel id="inputChannel">
    <int:interceptors>
        <int:wire-tap channel="logger"/>
    </int:interceptors>
</int:channel>

<int:channel id="outputChannel">
    <int:interceptors>
        <int:wire-tap channel="logger"/>
    </int:interceptors>
</int:channel>

<int:logging-channel-adapter id="logger" level="DEBUG" log-full-message="true"/>

<int:service-activator input-channel="inputChannel"
                   output-channel="outputChannel"
                   ref="echoService"
                   method="test"/>

<bean id="echoService"
    class="com.examples.EchoService" />

我还尝试创建一个 bean 和另一个用于输出的 serviceactivator,然后自动装配那个 bean 并调用它的 "send" 方法,但我不知道在那个发送方法中实现什么来发送一个留言。

如果是简单的 request/response 场景,请使用入站网关而不是通道适配器,框架会为您处理关联。这用于 the sample app。只需让您的 POJO 方法 return 回复有效负载。

如果您想向客户端发送任意消息(即不是 request/reply,而是说,进、出、出、进、出、出、出等)那么,是的,您需要构建自己的消息,插入 ip_connectionId header.

要发送它们,有几种选择:

outputChannel 注入您的代码

@Autowired
private MessageChannel outputChannel;

使用MessagingTemplate发送到频道(或者直接调用它的send(Message<?> message)方法)。

使用带有 void return 方法的 MessagingGateway 并将网关注入您的代码。

编辑:

注意,如果您想在收到任何消息之前开始发送消息,您可以通过 connection opened event.

获取连接 ID