Cannot get stream in socket java

Cannot get stream in socket java

Problem Description:


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



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

Here’s my src

Solution – 1

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:

try(ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()){
        System.out.println("Rcvd Stream");

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)

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.