来自 InputStream 的对象转换 - Spring 集成

Object conversion from InputStream - Spring integration

由于客户端-服务器应用程序中的序列化,我正在尝试通过 TCP 发送对象。 TCP 客户端是在 android 系统上编写的,我使用 ObjectOutputStream 发送一个对象。 TCP 服务器是用 spring 集成编写的,我尝试使用解串器读取这个对象。像这样:

<int-ip:tcp-connection-factory id="hosServer"
    serializer="connectionSerializeDeserialize"
    deserializer="connectionSerializeDeserialize" ..... >

在实现 Serializer 和 Deserializer 接口的 class 中,我从 InputSream 创建了 ObjectInputStream,这是反序列化器方法中的参数。在我尝试再次连接到服务器的那一刻,它工作正常。然后我在通过 readObject() 方法从 ObjectInputStream 读取对象时收到 EOFException。

public class CommandConverter implements Serializer<Command>, Deserializer<Command>{

    private ObjectInputStream ois = null;
    private ObjectOutputStream oos = null;
    private CommandBuilder commandBuilder = new CommandBuilder();

    public Command deserialize(InputStream inputStream) throws IOException {
        if (ois == null)
            ois = new ObjectInputStream(inputStream);
        Command cmd = null;
        try {
            cmd = (Command) ois.readObject();
        } catch (ClassNotFoundException e) {
            commandBuilder.setCommandBuilder(new ImproperCommandBuilder());
            commandBuilder.createCommand();
            cmd = commandBuilder.getCommand();
        } catch (InvalidClassException e) {
            commandBuilder.setCommandBuilder(new ImproperCommandBuilder());
            commandBuilder.createCommand();
            cmd = commandBuilder.getCommand();
        }
        return cmd;
    }

在 spring 集成中通过 TCP 发送对象的最佳方法是什么?

SerializerDeserializer 实现必须是线程安全的。实现这一点的最简单方法是使实现 stateless.

由于您在 class 中拥有这些属性,因此它们会在不同的调用之间共享。拥有这样的状态会使行为变得不可预测。

ObjectInputStreamObjectOutputStream 不是为共享状态而设计的。

因此,您必须在调用 deserialize() 时始终创建 ObjectInputStream

ObjectInputStream ois = new ObjectInputStream(inputStream);

等等。