开发者

Stop and wait UDP server

I am trying to progr开发者_JAVA百科am a Java stop-and-wait UDP server and I have gotten this far with the server but I am not sure where to go next. I want the client to send a message to the server, set a timeout, wait for a response, if it doesn't get one, then resend the packet, if it does then increment the sequence no. until it get to ten and keep send and receiving messages with the server.

I have gotten this far, how do I fix this ? :

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();
      }
      }}}}


The first problem I can see (apart from the mistyped variable names which will stop your code compiling) is your socket timeout: if the socket timeout expires, the receive function will throw a SocketTimeoutException which your code does not handle. receive does not return a value, so the result can't be compared with null. Instead, you need to do something like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜