Sending Objects over Java Socket really slow

笑着哭i 提交于 2019-12-08 03:58:20

问题


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);
    }
}

回答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



回答2:


I had the same problem, simple connection had ping about 400ms. Try add this line after socket creating: socket.setTcpNoDelay(true);



来源:https://stackoverflow.com/questions/27924458/sending-objects-over-java-socket-really-slow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!