如何在spring集成中写回socket

oyjwcjzk  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(301)

我有一个springboot项目,它使用spring集成进行tcp通信。我向服务器发送一个请求,服务器首先返回一个ack,然后返回实际响应。服务器希望我在得到响应时发送ack。我如何在同一个插座上发送此ack以表明我收到了响应?
这是我的连接工厂和出站网关:

<int-ip:tcp-connection-factory id="tcpClientFactory"
                               type="client"
                               host="${host}"
                               port="${port}"
                               so-keep-alive="true"
                               single-use="true"
                               using-nio="true"
                               serializer="messageSerializer"
                               deserializer="messageSerializer"/>

<ip:tcp-outbound-gateway id="outboundGateway"
                         connection-factory="tcpClientFactory"
                         request-channel="toTcpAdapterChannel"
                         reply-channel="fromTcpAdapterChannel"
                         auto-startup="true"
                         request-timeout="90000"
                         remote-timeout="90000"
                         reply-timeout="90000"/>

这是我的序列化和反序列化程序:

@Override
public void serialize(byte[] bytes, OutputStream outputStream) throws IOException {
        super.serialize(bytes, outputStream);

        if (logger.isDebugEnabled()) {
            ByteArrayOutputStream btO = new ByteArrayOutputStream();
            super.serialize(bytes, btO);
            logger.debug("Message(Serialized) bytes:" + HexUtils.toHexString(btO.toByteArray()));

    }
}

@Override
public byte[] deserialize(InputStream inputStream) throws IOException {
    boolean allMessageRead = false;
    byte[] incomingArray = new byte[0];
    while (!allMessageRead) {
        int length = inputStream.available();
        incomingArray = new byte[length];
        this.read(inputStream, incomingArray, false);
        if (length == 1) {
            logger.info("Available length of inputStream is: {}", length);
            logger.info("Length is 1. Incoming byte: {}", HexUtils.toHexString(incomingArray));
            return null;
        } else if (length > 1) {
            System.out.println("Message DUMP-1! " + HexUtils.toHexString(incomingArray));
            incomingArray = Arrays.copyOfRange(incomingArray, 1, length - 3);
            allMessageRead = true;
        }
    }

    return incomingArray;
}
iq3niunx

iq3niunx1#

您不能使用网关发送任意消息,只能请求/回复。
要执行所需操作,必须改用协作通道适配器。
请参阅文档:
https://docs.spring.io/spring-integration/docs/current/reference/html/ip.html#ip-协作适配器
编辑
或者,一个更简单的解决方案可能是使用连接拦截器。当收到结果时,拦截器可以发送ack。
https://docs.spring.io/spring-integration/docs/current/reference/html/ip.html#ip-拦截器

相关问题