rdt3.0發送方程式(Java實現)

來源:互聯網
上載者:User

這個是在參考了下老師給的代碼^_^.比淩晨發的那個C實現的在介面上要友好很多..而且個人感覺更清晰...

import javax.swing.*;
import java.awt.event.*;
import javax.swing.Timer;

public class Sender
{
   public static void main(String [] args)
   {
     String input;
     int counter = 0;
     int configure;

     /* 輸入要發送的資料 */  
     input = JOptionPane.showInputDialog("input the sending data!");
     /* 為發送的資料包註冊相應的時鐘監聽器 */ 
     Timer aTimer = new Timer(5000 , new SenderListener(input , counter%2));
     /* 啟動時鐘監聽器 */
     aTimer.start();
    
     do
     {
      /* 接收回應方的相關資訊 */
 configure = answerToSender();
 while(true)
 {
    /* 如果資料包已經成功接收,則終止相應的時鐘監聽器
    /* 否則資料包重發,時鐘監聽器繼續監聽 */
    if(configure == counter%2)
    {
       aTimer.stop();
       break;
    }
          
    else configure = answerToSender();
 }
 input = JOptionPane.showInputDialog("continue?(Y/N)");
 if(input.equals("N") || input.equals("n")) break;
       
 input = JOptionPane.showInputDialog("input the sending data!");
 aTimer = new Timer(5000 , new SenderListener(input , ++counter%2));
 aTimer.start();
     }while(true);
   
     System.exit(0);
  }
 
  public static int answerToSender()
  {
     String input = JOptionPane.showInputDialog("response to sender(0/1)");
     return Integer.parseInt(input);
  }
}

/* 實現了ActionListener監聽器介面的自訂類,在該類中必須實現
  ActionListener介面中的actionPerformed(ActionEvent)方法,該
  方法在時間間隔到達你所定義的時間間隔時會被自動調用 */
class SenderListener implements ActionListener
{
   private String series;
   private int sequenceNumber;

   /* 構造器,在對象初始化時被調用 */ 
   public SenderListener(String series ,int counter)
   {
      this.series = series;
      sequenceNumber = counter;
      System.out.println("the datas: '" + series + "' have been sended!/n"
     + "          " + " and its sequence number is: " + sequenceNumber + "/n");
   }
 
   public void actionPerformed(ActionEvent aevent)
   {
      System.out.println("the datas: '" + series + "' recieved failurely!");
      sendAgain();
   }
 
   public void sendAgain()
   {
      System.out.println("the datas: '" + series + "' have been sended again!/n"); 
   }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.