我这里有一个 UDP ping 客户端。我不知道我是否做对了,但我认为如果我设置127.0.0.1
为 IP 地址它会起作用。但如果我将其设置为例如 Google 的 IP 地址,则不会。我得到一个例外: java.net.SocketTimeoutException: Receive timed out
.
import java.io.*;
import java.net.*;
import java.util.*;
public class PingClient {
private static final int AVERAGE_DELAY = 0;
public static void main(String[] args) throws Exception {
int port = 4997;
DatagramSocket socket = new DatagramSocket(port);
for(int i=1;i<=10;i++) {
byte[] buf = new byte[1024] ;
Calendar cal=Calendar.getInstance();
String ping="PING "+ i +" "+cal.getTimeInMillis()+" ms"+"\r\n";
buf=ping.getBytes("UTF-8");
InetAddress address = InetAddress.getByName("69.63.176.11");
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, port);
packet.setData(buf);
socket.send(packet);
Thread.sleep( 10* AVERAGE_DELAY);
DatagramPacket server_response = new DatagramPacket(new byte[1024], 1024);
socket.setSoTimeout(1000);
socket.receive(server_response);
printData(server_response);
}
}
}