2015-09-28 3 views
2

Как я могу реализовать активатор службы для чтения определенного количества байтов?TcpInboundGateway - Чтение определенного количества байтов

Мой context.xml,

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:int="http://www.springframework.org/schema/integration" 
    xmlns:int-ip="http://www.springframework.org/schema/integration/ip" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
     http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd 
     http://www.springframework.org/schema/integration/ip http://www.springframework.org/schema/integration/ip/spring-integration-ip.xsd"> 

    <int:annotation-config /> 

    <context:component-scan base-package="com.spring.integration.tcp" /> 

<bean id="tcpDeserializer" 
    class="org.springframework.integration.ip.tcp.serializer.ByteArrayLengthHeaderSerializer"> 
    <property name="maxMessageSize" value="300" /> 
</bean> 

    <int-ip:tcp-connection-factory id="tcpConnectionFactory" type="server" port="9070" using-nio="true" deserializer="tcpDeserializer" /> 

    <int:channel id="tcpRequestChannel" /> 

    <int-ip:tcp-inbound-gateway id="tcpInboundGateway" connection-factory="tcpConnectionFactory" request-channel="tcpRequestChannel" /> 

    <bean id="messageHandler" class="com.spring.integration.tcp.MessageHandler" /> 

    <int:service-activator id="tcpServiceActivator" input-channel="tcpRequestChannel" ref="messageHandler" method="receiveAndSend" /> 

</beans> 

Мой обработчик сообщений

package com.spring.integration.tcp; 

import java.io.InputStream; 
import java.util.Arrays; 


public class MessageHandler 
{ 
    public byte[] receiveAndSend(final InputStream inputStream) throws Exception 
    { 
     int bytesToRead = 50; 
     final byte[] requestMessageBytes = new byte[bytesToRead]; 
     int read = 0; 
     while (bytesToRead > read) 
     { 
      final int c = inputStream.read(requestMessageBytes, read, bytesToRead - read); 
      if (c == -1) 
      { 

       throw new Exception("EOF"); 
      } 
      read += c; 
     } 
     System.out.println("server received - length [" + requestMessageBytes.length + "] bytes " + Arrays.toString(requestMessageBytes)); 
     final byte[] responseMessageBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; 
     System.out.println("server sending - " + Arrays.toString(responseMessageBytes)); 
     return responseMessageBytes; 
    } 
} 

Я хотел бы прочитать первые 4 байта и определяет входящий длину сообщения (от первых 4 байта), а затем прочитать байты сообщений, длина которых задается с помощью первых 4 байтов.

После добавления десериализатора я получаю следующее исключение. Хотя я послать массив байт длины 161.

final byte[] data = new byte[] { 2,....}; 

Exception,

Sep 28, 2015 7:03:28 PM org.springframework.integration.ip.tcp.connection.TcpNetConnection handleReadException 
SEVERE: Read exception localhost:54756:9070:a580527b-95bd-42c7-b1cc-e0726b433199 IOException:Message length 38159362 exceeds max message length: 300 

Если клиент базироваться на весенней интеграции, чтобы иметь возможность отправить сообщение на сервере весны на основе интеграции?

+0

Вопрос обновляется после добавления десериализации. – joshu

ответ

1

Вы должны настроить ByteArrayLengthHeaderSerializer как deserializer по определению <int-ip:tcp-connection-factory>.

Смотрите свои JavaDocs для получения дополнительной информации:

* The default length field is a 4 byte signed integer. During deserialization, 
* negative values will be rejected. 
* Other options are an unsigned byte, and unsigned short. 
+0

См. [Документацию] (http://docs.spring.io/spring-integration/reference/html/ip.html#connection-factories) о стандартных (де) сериализаторах, предоставляемых инфраструктурой. –

+0

Не используйте форматирование кода для текста, который не является кодом. – EJP

+0

JavaDoc - это код. Не вижу причин злоупотреблять своим правом редактировать по этой причине ... –

Смежные вопросы