在套接字服务器端编程中使用ObjectInputStream时出现StreamCorruptedException

时间:2015-06-26 20:40:38

标签: java sockets server

我正在编写一个套接字服务器端编程,其中客户端首先发送int 1以便用于注册并发送一个字符串对象数组。然后我将该信息存储到文件中,并将带有更多信息的对象返回给客户端。

但问题是当客户端连接并输入任何数字时,会发生 StreamCorruptedException 异常。

我删除了while循环中的所有行,除了getInt行以接收来自客户端的输入,然后也发生了相同的错误。

例外是

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

  try{

        inputFromClient = new DataInputStream( new BufferedInputStream(socket.getInputStream())); 
    outputToClient  = new DataOutputStream( new BufferedOutputStream
                                    (socket.getOutputStream()));

    objOutputToClient  = new ObjectOutputStream( new BufferedOutputStream(socket.getOutputStream()));
    objOutputToClient.flush();
    objOutputToClient.reset();


    try{
         //the exception occurs here
        //the java.io.StreamCorruptedException: invalid stream header: 00000000

        objInputFromClient  = new ObjectInputStream( new
        BufferedInputStream(socket.getInputStream()));
        objInputFromClient.reset();
    }
    catch(IOException e){
        System.out.println("Exception in HandleAClient " + e);
        e.printStackTrace();           
    } 

   while( true ){
        int getInt = inputFromClient.readInt();     

        switch ( getInt ){
        case 1 : // Get object for registration
            object = objInputFromClient.readObject();

            string = registerLogin.register(socket, object);                
            objOutputToClient.writeObject(string);
            break;
             default: string[0] = "9";
            objOutputToClient.writeObject(string);
           }
    }
   }
  catch(IOException e){
        System.out.println("Exception in HandleAClient " + e);
        e.printStackTrace();           
    } 

catch (ClassNotFoundException e) {
    System.out.println("Exception in HandleAClient" + e);
    e.printStackTrace();   
}

创建问题的代码仅限于此:

    objInputFromClient  = new ObjectInputStream( new BufferedInputStream 
    (socket.getInputStream()));

0 个答案:

没有答案