views:

57

answers:

2

My server keeps getting this error when I run the client:

Exception in thread "main" java.io.EOFException
    at java.io.DataInputStream.readInt(Unknown Source)
    at java.io.ObjectInputStream$BlockDataInputStream.readInt(Unknown Source)
    at java.io.ObjectInputStream.readInt(Unknown Source)
    at MyServer.main(MyServer.java:10)

Here is the server code:

import java.net.*;
import java.io.*;

public class MyServer{
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(40);
        Socket clientSocket = serverSocket.accept();
        ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
        System.out.println(in.readInt());
        serverSocket.close();
        System.exit(0);
    }
}

And here is the client code:

import java.io.*;
import java.net.*;

public class MyClient {
    public static void main(String[] args) throws IOException {

        Socket socket = new Socket("localhost", 40);
        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());     
        out.writeInt(5);
        socket.close();
        System.exit(0);
    }
}
+2  A: 

You should flush your ObjectOutputStream before closing the Socket.

Bombe
+2  A: 

Try adding

out.flush();

just before

socket.close();
sfussenegger
it worked. Thank you! ^_^
William