Astraioz Astraioz - 10 months ago 66
Java Question

Sending Objects over Java Socket really slow

I can't figure out why my Java Server with

Socket
and
ServerSocket
is that slow while sending objects. Here a small ping program to demonstrate my problem. If I run both client and server on the same machine, everything is fine ofc (<1ms ping time). However, if I move the Server to a Linux machine I get a ping time of >500ms (ping via command line to that machine says 20ms).

Thanks in advance




Server:

public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(Integer.parseInt(args[0]));
Socket socket = serverSocket.accept();

ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

oos.writeObject(System.currentTimeMillis());
long time = (long)ois.readObject();

System.out.println(System.currentTimeMillis()-time+" ms");

} catch (Exception e) {
System.out.println("Some error occured");
System.exit(1);
}
}


Client:

public static void main(String[] args) {
try {
Socket socket = new Socket(args[0], Integer.parseInt(args[1]));

ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

long time = (long)ois.readObject();
oos.writeObject(time);

} catch (Exception e) {
System.out.println("Some error occured");
System.exit(1);
}
}

Answer Source

I looked around the web a bit and you are not the only person with this problem. This post also describes the same issue,

Basically, what you should do is instead of:

ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

You should write:

ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));

And periodically you would write:

oos.flush();//Write after you send data
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download