Home > Net >  Cannot get stream in socket java
Cannot get stream in socket java

Time:12-06

Source:

while (true) {
  System.out.println("Waiting");
  ois = new ObjectInputStream(socket.getInputStream());
  System.out.println("Rcvd Stream");
  client listener.onDataReceived(ois.readObject());
}

Output

Waiting 

Cannot get input stream. What am I doing wrong here?

Here's my src https://github.com/Saakethjayarama/JavaSocket/tree/main

CodePudding user response:

The constructor of ObjectInputStream reads some data and waits until the data is read. Make sure it is sent (and flushed) before on the other side:

try(ObjectOutputStream oos=new ObjectOutputStream(socker.getOutputStream())){
    oos.flush();//make sure the data is actually sent
}

Make sure to flush after creating the ObjectOutputStream and before creating the ObjectInputStream - ideally on both sides. You should flush between writing and reading something whenever it needs to be written before being read.

Aside from that, you might want to create the ObjectInputStream once (before the loop) and read data multiple times using the same ObjectInputStream:

System.out.println("Waiting");
try(ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()){
    while(true){
        System.out.println("Rcvd Stream");
        clientListener.onDataReceived(ois.readObject());
    }
}

This also uses a try-with-resources block in order to make sure the stream (and socket) is properly closed.

Also note that

Deserialization of untrusted data is inherently dangerous and should be avoided. Untrusted data should be carefully validated according to the "Serialization and Deserialization" section of the Secure Coding Guidelines for Java SE. Serialization Filtering describes best practices for defensive use of serial filters.

Deserializing (untrusted) data from the network leads to denial of service (typically easy to exploit) up to remote code execution attacks (more difficult to exploit) as it may create/deserialize (almost) arbitrary object graphs.

(from the Javadoc of ObjectInputStream)

  • Related