java.io.StreamCorruptedException:无效的流标题:00000000

时间:2011-12-12 11:38:18

标签: java serialization

我正在尝试实现对象序列化,但仍然遇到了StreamCorruptedException。

在服务器端:

public class MulticastServer {
                public static void main(String[] args) throws java.io.IOException {
                new MulticastServerThread().start();
                }
} 

哪个电话:

public class MulticastServerThread extends QuoteServerThread {
                 boolean moreQuotes=true;
public void run() {
  while (moreQuotes) {
  try {
    byte[] buf = new byte[256];
    String dString="Server";
    System.out.println(dString);
    buf = dString.getBytes();

    InetAddress group = InetAddress.getByName("230.0.0.1");
    DatagramPacket packet = new DatagramPacket(buf, buf.length,
                                               group, 4446);

    socket.send(packet);

    ObjectInputStream is=null;

    ByteArrayInputStream byteStream = new ByteArrayInputStream(recvBuf);
    is = new ObjectInputStream(new BufferedInputStream(byteStream));

    Object o1=(Object)is.readObject();
    System.out.println(o1.a);

    is.close();
    socket.close();
    }}}}

服务器和客户端上的Object类:

public class Object implements Serializable{
private static final long serialVersionUID=1L;
int a=10;
}

和客户端代码:

public class MulticastClient {
public static void main(String[] args) throws IOException {
MulticastSocket socket = new MulticastSocket(4446);
InetAddress address = InetAddress.getByName("230.0.0.1");
socket.joinGroup(address);

Object o1=new Object();

DatagramPacket packet;

for (int i = 0; i < 5; i++) {
  byte[] buf = new byte[256];
  packet = new DatagramPacket(buf, buf.length);
  socket.receive(packet);

  String received = new String(packet.getData());
  System.out.println("received data" +received);

  ObjectOutputStream os = null;
  ByteArrayOutputStream byteStream = new ByteArrayOutputStream(15000);
            os = new ObjectOutputStream(new BufferedOutputStream(byteStream));
            os.flush();
            os.writeObject((Object)o1);
            System.out.println(o1.a);
            os.flush();
 }
 socket.leaveGroup(address);
 socket.close();
 }
 }

我已经完成了所有这些:

  1. 将所有类放在两台机器上的相同路径下
  2. 附加休息并尝试找出问题所在
  3. 有人可以帮帮我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

如果您尝试通过UDP进行对象序列化,则需要将对象序列化为数据包的字节数组,并从接收端读取该对象。有一篇旧的Java World文章:Object transport via datagram packets,你可能觉得它很有用。

看起来您想要实现双向通信:

server -> send packet
client -> receive packet
client -> send object
server -> receive object

我不确定这对你有多大帮助(特别是如果你有多个客户)。

但至少需要进行以下更改才能使任何工作正常运行:

  • 发送数据包后,您的服务器代码需要进行阻止receive调用。
  • 客户端代码需要send数据包中的对象。