Search code examples
javaclient-servereofexception

Client-Server using socket: Exception in thread "main" java.io.EOFException


I am writing simple client-server program where server is listening for all incoming connections and accepts them. Once accepted, client sends data (integer) to server and server echoes back the integer to client. This part works fine. Additionally client is sending data in succession (using while loop) on established connection, and thats where i hit a "java.io.EOFException" exception.

Server

listening on port : 3344

Received : 1 from client

listening on port : 3344

client

Enter Data to send: 1

Server replied : 1

Enter Data to send: 2

Exception in thread "main" java.io.EOFException at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2626) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1321) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373) at Node.main(Node.java:28)

Client Code

    int serverPort = 3344;
    Scanner sc = new Scanner(System.in);

    Socket clientSocket = new Socket("localhost", serverPort);

    ObjectOutputStream write = new ObjectOutputStream(clientSocket.getOutputStream());
    ObjectInputStream read = new ObjectInputStream(clientSocket.getInputStream());
    Integer writeData = new Integer(0);

    while (true) {
        System.out.println("Enter Data to send: ");
        writeData = sc.nextInt();

        write.writeObject(writeData);
        write.flush();
        Integer obj = (Integer) read.readObject();
        if (obj.intValue() == -1) {
            break;
        }
        System.out.println("Server replied : " + obj.toString());
        System.out.println();
    }

    write.close();
    read.close();

    clientSocket.close();

Server Code

        while (true) {
        System.out.println("listening on port : " + listenPort);
        try {
            clientSocket = listener.accept();

            write = new ObjectOutputStream(clientSocket.getOutputStream());
            read = new ObjectInputStream(clientSocket.getInputStream());

            int readInt = (Integer) read.readObject();

            System.out.println("Received : " + readInt + " from client");

            write.writeObject((Object) readInt);
            write.flush();

            //break;
        }
        finally {
            write.close();
            read.close();
            clientSocket.close();
            //listener.close();
        }

Solution

  • Your client connects to the server outside the loop where your server closes client connection inside the loop.

    Which means the client tries to write data to an output stream which belongs to an already closed connection.