2011-12-12 70 views
3

我想實現對象序列化,但卡在StreamCorruptedException。java.io.StreamCorruptedException:無效的流標頭:00000000

在服務器端:

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(); 
    }}}} 

和對象類的服務器和客戶端:

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. 重視休息,並嘗試找出問題的所在

能有人幫我?謝謝!

+0

我很努力地看到客戶端和服務器中的ByteArray [Input | Output]流是如何工作的。你期望他們連接嗎? – sudocode

+0

哦。我現在明白了。但是如何讓服務器等到客戶端發送它? –

+0

您應該能夠接收()等待,直到有數據包。 –

回答

1

如果您嘗試通過UDP進行對象序列化,則需要將對象序列化到數據包的字節數組中,然後從接收端讀取該對象。有一篇舊的Java World文章:Object transport via datagram packets,您可能會發現它很有用。

它看起來像你想實現一個雙向通信:

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

我不知道這是怎麼回事制定出適合你(特別是如果你有多個客戶端)。

但至少將需要以下變化得到任何工作:

  • 您的服務器代碼將需要發送的數據包後做阻塞receive電話。
  • 客戶端代碼將需要send數據包中的對象。
相關問題