2011-03-17 138 views
0

我正在嘗試編寫一個Java停止等待UDP服務器,並且我已經與服務器得到了這一點,但我不確定接下來要去哪裏。我希望客戶端向服務器發送消息,設置超時,等待響應,如果它沒有得到響應,然後重新發送數據包,如果它確實然後遞增序列號。直到它達到10並且保持與服務器的發送和接收消息。停止並等待UDP服務器

我已經得到了這麼多,我該如何解決這個問題? :

import java.io.*; 
import java.net.*; 

public class Client { 
    public static void main(String args[]) throws Exception { 

    byte[] sendData = new byte[1024]; 
    byte[] receiveData = new byte[1024]; 
    InetAddress IPAddress = null; 

    try { 
     IPAddress = InetAddress.getByName("localhost"); 
    } catch (UnknownHostException exception) { 
     System.err.println(exception); 
    } 

    //Create a datagram socket object 
    DatagramSocket clientSocket = new DatagramSocket(); 
    while(true) { 
     String sequenceNo = "0"; 
     sendData = sequenceNo.getBytes(); 
     DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 6789); 
     clientSocket.send(sendPacket); 
     clientSocket.setSoTimeout(1); 
     DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
     if(clientSocket.receive(receivePacket)==null) 
     { 
     clientSocet.send(sendPacket); 
     }else { //message sent and acknowledgement received 
      sequenceNo++; //increment sequence no. 
     //Create a new datagram packet to get the response 
     String modifiedSentence = sequenceNo; 
     //Print the data on the screen 
     System.out.println("From : " + modifiedSentence); 
     //Close the socket 
     if(sequenceNo >= 10) { 
     clientSocket.close(); 
     } 
     }}}} 

回答

1

我可以看到(除了輸錯的變量名,這將阻止你的代碼編譯)第一個問題是您的套接字超時:如果套接字超時,receive功能將拋出一個SocketTimeoutException你的代碼呢不處理。 receive does not return a value,所以結果不能與null比較。相反,你需要這樣做:

try { 
    clientSocket.receive(receivePacket); 
    sequenceNo++; 
    ... // rest of the success path 
} catch (SocketTimeoutException ex) { 
    clientSocket.send(sendPacket); 
}