java.io.StreamCorruptedException: invalid stream header: 73720015

Incident code:

Server : Each time it receives a Message object from the socket, it prints the object.

while (true){
    
                
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                message=(Message) ois.readObject();
                System.out.println(message);            
}

Client : The input message is sent to the server.

ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

while (true){
    
                   
                System.out.println("请输入要发送的信息");
                String content = scanner.next();               
                oos.writeObject(new Message(content));//问题:这里由同一个oos进行写入
}

Problem principle:

Each time new ObjectOutputStream() is called, the writeStreamHeader() method is called to write a 4-byte StreamHeader to mark it as an object stream. When multiple objects are sent by the same ObjectOutPutStream, only one StreamHeader will appear, which means that the program cannot identify the number of objects in the stream.

ObjectOutStream constructor:

public ObjectOutputStream(OutputStream out) throws IOException {
    
      
        verifySubclass();  
        bout = new BlockDataOutputStream(out);  
        handles = new HandleTable(10, (float) 3.00);  
        subs = new ReplaceTable(10, (float) 3.00);  
        enableOverride = false;  
        writeStreamHeader();  
        bout.setBlockDataMode(true);  
        if (extendedDebugInfo) {
    
      
            debugInfoStack = new DebugTraceInfoStack();  
        } else {
    
      
            debugInfoStack = null;  
        }  
    }  

solution:

A new ObjectOutPutStream object is created every time writeObject is written.

Client:

 while (true){
    
    
                //发送信息
           System.out.println("请输入要发送的信息");
           String content = scanner.next();
           new ObjectOutputStream(socket.getOutputStream()).writeObject(new Message(content));//每一个对象仅对应一次write操作
          //oos.writeObject();
}

Guess you like

Origin blog.csdn.net/weixin_44866921/article/details/132753885