如何在有限的时间内(超时)从DatagramSocket仅读取块?

时间:2011-04-04 01:24:22

标签: java sockets network-programming datagram

我正在运行模拟网络数据包传输丢失。我的服务器应用程序有时不会将数据发送回我的客户端。

在我的客户端,我每隔10秒就对服务器运行一次ping操作。但是,如果我的服务器没有发回任何内容,我的客户端将等待,直到收到下一个数据包。如果我从服务器上没有得到任何东西,我怎么能继续下一次迭代呢?

//attempt to read from server
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    receivePacket.getData();

//client blocks on this line until something is received from server
    clientSocket.receive(receivePacket);
    String receivedFromServer = new String(receivePacket.getData());
    System.out.println("FROM SERVER:" + receivedFromServer);

1 个答案:

答案 0 :(得分:4)

您需要设置timeout

clientSocket.setSoTimeout(TIMEOUT_IN_MILLISECONDS)