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

博主发现了一个Java Server使用Socket与ServerSocket进行对象传输时出现的延迟问题。当客户端和服务器在同一台机器上运行时,延迟小于1毫秒,但将服务器迁移到Linux机器上后,延迟增加到500毫秒以上(而实际到该机器的ping时间只有20毫秒)。解决方案是通过在ObjectOutputStream和ObjectInputStream中添加BufferedOutputStream和BufferedInputStream,并在发送数据后调用flush()方法,显著减少了延迟。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

}

}

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值