資源簡介
使用java語言模擬GBN網絡協議。包含3個應用文件,3個源文件,1個使用說明。
可以模擬丟包,包差錯,正常傳送等情況,并且用圖形化的方式顯示出來。是居家旅行之極品。
代碼片段和文件信息
package?com.wuyadong.gbnreceiver;
import?java.io.IOException;
import?java.io.objectInputStream;
import?java.io.objectOutputStream;
import?java.net.Socket;
import?java.net.UnknownHostException;
import?java.util.Date;
import?javax.swing.JLabel;
import?javax.swing.JTextArea;
import?com.wuyadong.valueBean.Packet;
public?class?GBNReceiver?{
//服務器
String?serverIP?=?“127.0.0.1“;
int?serverPort?=?2345;
objectOutputStream?outputStream?=?null;
objectInputStream?inputStream?=?null;
Socket?clientSocket?=?null;
//發送方,接受方
Sender?sender;
Reciever?reciever;
int?expectedseqnum;
Packet?sndpkt?=?null;
//記錄器
String?record?=?null;
private?JTextArea?textArea?=?null;
private?JLabel?label?=?null;
public?void?setPara(String?ip)
{
this.serverIP?=?ip;
}
public?void?updateRecord()
{
this.textArea.setText(record);
this.label.setText(“expectedseqnum:?“+expectedseqnum);
}
public?GBNReceiver(JTextArea?textAreaJLabel?label)
{
this.textArea?=?textArea;
this.label?=?label;
sender?=?new?Sender();
reciever?=?new?Reciever();
//初始化expectedseqnumsndpkt
record?=?“初始化sndpktexpectedseqnum\n“;
expectedseqnum?=?0;
this.updateRecord();
int?checksum?=?sender.count_checksum(“ACK“);
sndpkt?=?sender.make_pkt(-1?“ACK“?checksum);
}
//建立連接,構造輸入輸出流
public?void?connect()
{
try?{
clientSocket?=?new?Socket(this.serverIPthis.serverPort);
this.outputStream?=?new?objectOutputStream
(clientSocket.getOutputStream());
this.inputStream?=?new?objectInputStream
(clientSocket.getInputStream());
record?+=?“連接服務器成功\n“;
this.updateRecord();
//啟動reciever類
new?Thread(this.reciever).start();
}?catch?(UnknownHostException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}?catch?(IOException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
}
public?void?close()
{
record?+=?“關閉連接“;
try?{
this.inputStream.close();
this.outputStream.close();
this.clientSocket.close();
}?catch?(IOException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
}
class?Sender{
//目標地址,源地址
String?source?=?“127.0.0.1“?;
int?sourceport=2345?;
String?destination?=?“127.0.0.1“?;
int?destinationport=2345?;
public?Packet?make_pkt(int?expectedSeqnumString?data
int?checksum)
{
//構建一個packet
Packet?packet?=?new?Packet(data
checksumsourcedestination
sourceportdestinationportexpectedSeqnum);
return?packet;
}
//用哈希碼進行check
int?count_checksum(String?data)
{
int?sum?=?0;
for(int?i?=?0;i? sum?+=?data.charAt(i);
return?sum;
}
public?void?udt_send(Packet?packet)
{
System.out.println(“發送packet包“);
try?{
outputStream.writeobject(packet);
}?catch?(IOException?e)?{
- 上一篇:android成績查詢系統
- 下一篇:回溯法解決旅行售貨員問題源代碼java
評論
共有 條評論