Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 停止并等待UDP服务器_Java_Sockets_Udp - Fatal编程技术网

Java 停止并等待UDP服务器

Java 停止并等待UDP服务器,java,sockets,udp,Java,Sockets,Udp,我正在尝试编写一个Java停止等待UDP服务器,我已经完成了这一步,但我不确定下一步该怎么做。我希望客户端向服务器发送消息,设置超时,等待响应,如果没有响应,则重新发送数据包,如果没有响应,则增加序列号,直到达到10,并与服务器保持发送和接收消息 我已经走了这么远,我该怎么解决这个问题 import java.io.*; import java.net.*; public class Client { public static void main(String args[]) throw

我正在尝试编写一个Java停止等待UDP服务器,我已经完成了这一步,但我不确定下一步该怎么做。我希望客户端向服务器发送消息,设置超时,等待响应,如果没有响应,则重新发送数据包,如果没有响应,则增加序列号,直到达到10,并与服务器保持发送和接收消息

我已经走了这么远,我该怎么解决这个问题

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

我看到的第一个问题(除了会停止代码编译的错误输入变量名)是套接字超时:如果套接字超时过期,
receive
函数将抛出一个
SocketTimeoutException
,而您的代码不处理它,因此,结果不能与
null
进行比较。相反,您需要这样做:

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