通过 Java Socket 发送对象真的很慢

Ast*_*ioz 2 java sockets connection server

我想不通,为什么我的Java服务器使用Socket,并ServerSocket是缓慢的,而发送的对象。这里有一个小 ping 程序来演示我的问题。如果我在同一台机器上同时运行客户端和服务器,一切都很好(<1ms ping 时间)。但是,如果我将服务器移到 Linux 机器上,我的 ping 时间会超过 500 毫秒(通过命令行对那台机器的 ping 时间为 20 毫秒)。

提前致谢


服务器:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

客户:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Gen*_*der 5

我在网上浏览了一下,你不是唯一有这个问题的人。这篇文章也描述了同样的问题

基本上,你应该做的是而不是:

ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
Run Code Online (Sandbox Code Playgroud)

你应该写:

ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
Run Code Online (Sandbox Code Playgroud)

并且定期你会写:

oos.flush();//Write after you send data
Run Code Online (Sandbox Code Playgroud)