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);
}
}
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
I had the same problem, simple connection had ping about 400ms. Try add this line after socket creating: socket.setTcpNoDelay(true);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.