2011-03-17 134 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); 
}