通过Java Socket发送对象真的很慢 [英] Sending Objects over Java Socket really slow
问题描述
我无法弄清楚为什么带有 Socket
和 ServerSocket
的Java Server在发送对象时这么慢。这里有一个小的ping程序来演示我的问题。如果我在同一台计算机上同时运行客户端和服务器,则一切正常(ping时间小于1毫秒)。但是,如果我将服务器移至Linux机器,则ping时间> 500毫秒(通过命令行对该机器执行ping操作表示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).
谢谢预先
服务器:
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);
}
}
推荐答案
I环顾了一下网络,您不是唯一遇到此问题的人。这篇帖子也描述了相同的问题,
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());
您应输入:
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
这篇关于通过Java Socket发送对象真的很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!