Good day to all! Faced a problem when packing and transferring an object between a client (Android) and a Server (Java).

A piece of the client side (packaging and shipping): @Override public boolean onTouch (View v, MotionEvent event) {

Point point = new Point(event.getX(), event.getY()); switch(event.getAction()){ case MotionEvent.ACTION_MOVE: try{ ObjectOutputStream outputStream = new ObjectOutputStream(this.clientConnection.getOutputStream()); outputStream.writeObject(point); outputStream.flush(); outputStream.close(); }catch(IOException e){ e.printStackTrace(); } break; } return true; } 

Server part: public void run () {

  System.err.println("Запущен поток выполнения для Клиента #" + this.clientID); try{ // Обертка потока ObjectInputStream inputStream = new ObjectInputStream(this.clientSocket.getInputStream()); try{ while(true){ // Десериализация объека Point point = (Point) inputStream.readObject(); System.err.println(point.x + " : " + point.y); } }catch(ClassNotFoundException e){ e.printStackTrace(); }catch(EOFException e){ e.printStackTrace(); } }catch(IOException e){ e.printStackTrace(); } } 

Log:

Running thread for Client # 0

26.444906: 275.00372 java.io.EOFException at java.io.ObjectInputStream $ BlockDataInputStream.peekByte (Unknown Source) at java.io.ObjectInputStream.readObject0 (Unknown Source) at java.io.ObjectInputStream.readObject0object0bject0 (Unknown Source) at java.io.ObjectInputStream.readObject0 (Unknown Source) at java.io.ObjectInputStream.readObject0 (Unknown Source) .mouseserver.Client.run (Client.java:72) at java.lang.Thread.run (Unknown Source)

    2 answers 2

    EOFException means that the stream reading from the socket received an EOF at the input. This is normal behavior, since in the client you close the socket with the call outputStream.close(); . If you catch this exception, consider that the client has ended normally and close the socket on your side. That's right:

     catch(EOFException e){ this.clientSocket.close(); // и выходить из сервера, или открывать и ждать следующий сеанс связи } 
    • Somewhere I heard the expression: "Programming on exceptions", they say it is not good? - kmaks
    • This is Java, EMNIP with her in another way does not work. - Vesper

    When receiving an object from a stream, I recommend writing it into a separate object of class Object, i.e.

     Object obj = objectInputStream.readObject(); 

    In the future, carry out transformations on this object.