這個是在參考了下老師給的代碼^_^.比淩晨發的那個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");
}
}