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

时间:2015-01-13 14:30:40

标签: java sockets connection server

我无法弄清楚为什么带有SocketServerSocket的Java Server在发送对象时速度很慢。这里有一个小ping程序来演示我的问题。如果我在同一台机器上同时运行客户端和服务器,那么一切都很好(< 1ms ping time)。但是,如果我将服务器移动到Linux机器上,我的ping时间大于500毫秒(通过命令行ping到该机器说20ms)。

提前致谢


服务器

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

客户端:

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

2 个答案:

答案 0 :(得分:4)

我在网上看了一下,你不是唯一有这个问题的人。这是post also describes the same issue

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

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

你应该写:

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

定期你会写:

oos.flush();//Write after you send data

答案 1 :(得分:1)

我遇到了同样的问题,简单的连接已经ping了大约400ms。尝试在套接字创建后添加此行:     socket.setTcpNoDelay(true);