How to check ObjectInputStream is empty in Java?

Viewed 485

im trying to implement a basic chat applcation via sockets but i have problem with ObjectInputStream. Im using both write-read methods in while(true) loop and compiling process got stuck when there is nothing to read and waits for it infinitly. Thus, i need to check wheter is it empty or not before read it.

Here is my codes.

Server:

Socket socket = server.accept();
        
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        
        oos.writeObject("Server connected!");
        oos.flush();
        
        String message = (String) ois.readObject();
        System.out.println(ois.available());
        txtChat.setText(message);
        
        while(true) {
            
            if(sendMessage) {
                
                oos.writeObject(txtMessage.getText());
                oos.flush();

                sendMessage = false;
            }
            
            while(!sendMessage) {
                message = (String) ois.readObject();
                txtChat.setText(txtChat.getText()+"\n"+"Client: "+message);
            }

            Thread.sleep(100);
        }

Client:

socket = new Socket(host.getHostName(), 9876);
        oos = new ObjectOutputStream(socket.getOutputStream());
        ois = new ObjectInputStream(socket.getInputStream());
        
        oos.flush();
    
        String message = (String) ois.readObject();
        txtChat.setText(message);
        
        while(true) {
            message = (String) ois.readObject();
            txtChat.setText(txtChat.getText()+"\n"+"Server: "+message);
            
            if(sendMessage) {
                oos.writeObject(txtMessage.getText());
                oos.flush();
                
                sendMessage = false;
            }
            
            
            Thread.sleep(100);
        }
    
1 Answers

The stream is either closed or open.

The input stream isn't aware that it is closed until you read something out of it. This is precisely why there exists no such isClosed() method on the stream.

You can read the bytes from the stream, into an object. At best you'll be able to construct the object. Else, you should handle the IO exception and decide accordingly.

Optionally, you can check how many bytes you can read without blocking. If it's 0, you're looking at an empty stream that is waiting for input.

inputStream.available() != 0 //handle exception
Related