我遇到了一个奇怪的问题,我无法弄清楚发生了什么。 所以基本上,当我尝试通过交换浮点数(使用DataInputStream和DataOutputStream)在服务器和客户端之间建立简单连接时,似乎有一个固定的ping限制,在具有openjdk的三台不同计算机上正好是40ms。
此外,我试图改变我发送浮点数的方式:
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();
}
}
}
给了我(在localhost上)通常的writeFloat:
已用时间:40毫秒
使用write():
已用时间:0毫秒
编辑:
显然,Mike's答案似乎解决了这个问题!使用writeFloat不再有40ms的延迟...
答案 0 :(得分:1)
窗?尝试增加发送的字节数。 Windows TCP / IP堆栈中存在(或者是)限制,等待获取更多字节以获取完整包发送的时间量。