【发布时间】:2014-07-13 05:27:02
【问题描述】:
我遇到了一个奇怪的问题,我不知道发生了什么。 所以基本上,当我尝试通过交换浮点数(使用 DataInputStream 和 DataOutputStream)在服务器和客户端之间建立一个简单的连接时,似乎有一个固定的 ping 限制,在三台不同的计算机上使用 openjdk 正好是 40 毫秒。
此外,我尝试更改发送浮点数的方式:
outs.write(ByteBuffer.allocate(4).putFloat(3.14f).array(), 0, 4);
它应该做同样的事情:
outs.writeFloat(3.14f);
这个奇怪的 ping 限制竟然消失了!
也许我对以下代码做错了什么:
客户端
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.io.IOException;
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.nio.ByteBuffer;
public class client {
private Socket sock;
private DataOutputStream outs;
private DataInputStream ins;
public client() throws IOException{
byte c;
sock = new Socket(InetAddress.getByName("localhost"),9998);
outs = new DataOutputStream(sock.getOutputStream());
ins = new DataInputStream(sock.getInputStream());
do{
long start = System.currentTimeMillis();
/* here is the thing */
//outs.write(ByteBuffer.allocate(4).putFloat(3.14f).array(), 0, 4); // either this outs
outs.writeFloat(3.14f); // or this one
outs.flush();
c = ins.readByte();
long stop = System.currentTimeMillis();
System.out.println("elapsed time: "+(stop-start)+"ms");
}while(c == (byte) 1);
}
public static void main(String[] args) {
try{
client client = new client();
} catch(SocketException e){
System.out.println("Socket disconnected");
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.ServerSocket;
import java.io.IOException;
import java.io.DataOutputStream;
import java.io.DataInputStream;
public class server extends Thread{
private DataOutputStream outs;
private DataInputStream ins;
public server(Socket sock) throws IOException{
System.out.println("client connected");
outs = new DataOutputStream(sock.getOutputStream());
ins = new DataInputStream(sock.getInputStream());
}
public void run(){
try{
while(true){
float f = ins.readFloat();
System.out.println("value: "+f);
outs.writeByte((byte) 1);
outs.flush();
}
} catch (IOException e) {
System.out.println("client disconnected");
}
}
public static void main(String[] args) {
try{
ServerSocket serverSock = new ServerSocket(9998);
while(true){
server server = new server(serverSock.accept());
server.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
这给了我(在本地主机上)通常的 writeFloat:
经过时间:40ms
使用 write():
经过时间:0ms
编辑:
显然,Mike's 的回答似乎解决了这个问题! writeFloat 不再有 40 毫秒的延迟...
【问题讨论】: