简体   繁体   English

通过TCP将对象(类)从C#客户端发送到Java服务器

[英]Send Object (Class) from C# Client to Java Server over TCP

i'm trying to send an object from c# to java over a TCP connection but it does not work. 我正在尝试通过TCP连接将对象从C#发送到Java,但是它不起作用。 Java tell me there is an error and i don't know why Java告诉我有错误,我不知道为什么

java.io.StreamCorruptedException: invalid stream header: 3C3F786D
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
    at java.io.ObjectInputStream.<init>(Unknown Source)
    at ClientThread.run(ClientThread.java:34)
    at java.lang.Thread.run(Unknown Source)

I googled it already but found no precise answer for my problem. 我已经用谷歌搜索了,但是没有找到我的问题的确切答案。 I have serialized my c# class with and xml serializer. 我已经使用xml序列化器序列化了我的c#类。 I've found the code on the internet. 我在互联网上找到了代码。

Here is the c# code 这是C#代码

        var cmd = new Command();
        cmd.setType(5);

        var xmlSerializer = new XmlSerializer(typeof(Command));

        using (var memoryStream = new MemoryStream())
        {
            xmlSerializer.Serialize(memoryStream, cmd);
        }

        String sendMsg = message + ";";
        try
        {
            if (tcp_stream.CanWrite)
            {
                xmlSerializer.Serialize(tcp_stream, cmd);
            }
            tcp_stream.Flush();
        }
        catch (Exception exception)
        {
            MessageBox.Show("Error..... " + exception);
        }

And the Java server code is Java服务器代码是

try {

    ObjectOutputStream sOutput = new ObjectOutputStream(socket.getOutputStream());
    ObjectInputStream sInput = new ObjectInputStream(
    socket.getInputStream());
    this.message = (Message) sInput.readObject();
    System.out.println("MessageType: " + this.message.getType());
}
catch (IOException e) {
    System.out.println("Can not get message. " + e.getMessage());
    e.printStackTrace();
    break;
}
catch (ClassNotFoundException e) {
    e.printStackTrace();
}

Thanks for any answers. 感谢您的任何答案。 Any help is appreciated. 任何帮助表示赞赏。

Java binary serialization and .NET XML serialization are not compatible with each other. Java二进制序列化和.NET XML序列化彼此不兼容。 Java binary serialization is compatible with itself and that is pretty much it. Java二进制序列化与其自身兼容,仅此而已。 You need to pick a common format which can be serialized and deserialized by both. 您需要选择一种可以同时被序列化和反序列化的通用格式。 Some examples might include some flavor of XML or JSON or BSON, Google Protobuf, etc. 一些示例可能包括某种形式的XML或JSON或BSON,Google Protobuf等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM