V
V
Vadim Gush2014-04-27 19:16:20
Java
Vadim Gush, 2014-04-27 19:16:20

Why does the command in Java not work when working with input?

The point is this. Here is the code:

try {
        
        connect = server.accept();
        output = new ObjectOutputStream(connect.getOutputStream());
        input = new ObjectInputStream(connect.getInputStream());
        output.writeObject("Сообщение получено! (" + input.readObject() + ")");
        System.out.println("Client write: " + (String)input.readObject());  //<----
        
      } catch (UnknownHostException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (HeadlessException e) {
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }

Why is output.writeObject("Message received! (" + input.readObject() + ")"); but the subsequent command is not. (I showed it with an arrow)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Keyn Din, 2014-04-27
@Lure_of_Chaos

It is necessary that the second Object be written to the input.
If you set two copies. applications with this code (i.e. read, then write, then expect to receive it), try output.flush() after output.writeObject
Also in this case (when the application is both a server and a client for itself), it matters:
1. initialization of ObjectOutputStream before ObjectInputStream
2. so that there is a writeObject before reading readObject, because During initialization, ObjectInputStream waits for people to write to it immediately, otherwise it blocks the stream.
In any case, there is blocking input / output, so you can’t do without a single thread.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question