[英]Sending Objects over Java Socket really slow
I can't figure out why my Java Server with Socket
and ServerSocket
is that slow while sending objects. 我不知道为什么我的带有
Socket
和ServerSocket
Java Server在发送对象时这么慢。 Here a small ping program to demonstrate my problem. 这里有一个小的ping程序来演示我的问题。 If I run both client and server on the same machine, everything is fine ofc (<1ms ping time).
如果我在同一台计算机上同时运行客户端和服务器,则一切正常(ping时间<1ms)。 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).
但是,如果将服务器移至Linux机器,则ping时间> 500ms(通过命令行对该计算机执行ping操作表示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. 我遇到了同样的问题,简单的连接ping了大约400ms。 Try add this line after socket creating:
socket.setTcpNoDelay(true);
尝试在创建套接字后添加以下行:
socket.setTcpNoDelay(true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.