【问题标题】:Stop and wait UDP server停止并等待 UDP 服务器
【发布时间】:2011-03-17 21:37:45
【问题描述】:

我正在尝试编写一个 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();
      }
      }}}}

【问题讨论】:

    标签: java sockets udp


    【解决方案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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多