📄 router.java
字号:
import java.net.*;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.lang.Integer;
import java.util.concurrent.*;
public class Router {
//public static HashMap<Integer,Integer> isTimeOut=new HashMap<Integer,Integer>();
public static boolean flagx=false;
public static final int commonCommandPort=2360;
public static HashSet<Integer> allPorts=new HashSet<Integer>();//储存所有port以检查新输入的port是否合法
public static HashMap<Integer,Integer> relation=new HashMap<Integer,Integer>();
//这是显示端口号和ID之间的映射,前一个是port,后一个是ID
//建立这样一个映射是为了建立路由表的时候方便点
public static HashMap<Integer,Integer> revrelation=new HashMap<Integer,Integer>();
public static HashSet<Integer> activeRouter=new HashSet<Integer>();//里面存储的是活动的路由器的id
public static boolean DataFlag=false;
private int routerId; //路由器ID
private int routerPort; //路由器端口
private int commandPort=commonCommandPort; //命令端口通用
private DataPacket datapacket;
private HashSet<Integer> neighborPorts; //本路由器的邻接端口,和下面的neighbors对应
private HashMap<Integer,String> RoutingTable; //"Integer" is destinationId,"String" is distance (abort port)
private Packets pks;
private HashSet<Integer> destination=new HashSet<Integer>();
public void retDataPacket(DataPacket dpk)
{
datapacket=dpk;
}
public void fillDataPacket(Integer des,String data)
{
datapacket= new DataPacket(des,data);
}
public DataPacket getDataPacket()
{
return datapacket;
}
public void fillDestination(Integer input)
{
destination.add(input);
}
public HashMap<Integer,String> getRoutingTable()
{
return RoutingTable;
}
public int getID()
{
return routerId;
}
public int getRouterPort()
{
return routerPort;
}
public HashSet<Integer> getNeighborPorts()
{
return neighborPorts;
}
public HashSet<Integer> getDestination() //建立目的节点是为了更方便地判断一个最终节点是否在路由表中
{
return destination;
}
public Integer getRouterId()
{
return new Integer(routerId);
}
public Packets getPackets()//将本路由器的路由表包装起来,由于路由随时会变,所以,每次在发送前都要运行这个
{
pks=new Packets();
Iterator it=(this.getDestination()).iterator();
while(it.hasNext())
{
Integer des=(Integer)(it.next());
//Packet p=new Packet(this.getRouterId(),des,RoutingTable.get(des));
pks.intputPacket(new Packet(this.getRouterId(),des,RoutingTable.get(des)));//RoutingTable.get(new Integer(des))是得到DV
}
return pks;
}
synchronized void processDV(Packets pks) //处理接收过来的包
{
/*
Iterator itt=neighborPorts.iterator();
while(itt.hasNext())
{
Integer neiID=relation.get((Integer)(itt.next()));
int count = (isTimeOut.get(neiID)).intValue();
count++; //先加了再说
if(count==4) //如果已经三次没有收到包
{
activeRouter.remove(neiID);
}
else
{
(Router.isTimeOut).remove(neiID);
(Router.isTimeOut).put(neiID,new Integer(count));
}
} //上面是进行初始的判断
*/
String [] count=null;
int isId=routerId;
HashSet<Packet> Packets=pks.getPackets();
Iterator it=Packets.iterator();
while(it.hasNext())
{
Packet pet=(Packet)it.next();
/*
Integer whosendpks=pet.getSender(); //如果邻节点发送了数据包,则通过whosendpks将标志改写
if(activeRouter.contains(whosendpks)!=true)
{
activeRouter.add(whosendpks);
(Router.isTimeOut).remove(whosendpks);
(Router.isTimeOut).put(whosendpks,new Integer(0));//0是计数
}
else
{
(Router.isTimeOut).remove(whosendpks);
(Router.isTimeOut).put(whosendpks,new Integer(0));//0是计数
}
*/
Integer des=pet.getDestination();
if(routerId!=(pet.getDestination()).intValue())
{
destination.add(des);
String DV=pet.getDV();
String newDV=((Integer)pet.getSender()).toString()+" "+DV;
String [] DV2=(newDV).split(" ");
if(RoutingTable.containsKey(des)!=true)//如果路由表中没有这个最终节点的路由,则直接加入路由表
{
RoutingTable.put(des,newDV);
}
else
{
count=((RoutingTable.get(des)).split(" "));
int i=count.length;
if(DV2.length<i)
{
RoutingTable.remove(des);
RoutingTable.put(des,newDV);
}
}
}
}
}
public Router(int rId,int rPort,HashSet<Integer> neiPorts)
{
//刚开始建立路由器的时候应该初始化它的路由表,也就是把邻节点加进去
routerId=rId;
routerPort=rPort;
neighborPorts=new HashSet<Integer>();
neighborPorts=neiPorts;
RoutingTable=new HashMap<Integer,String>();//对路由表进行初始化是在路由器之间进行通信的时候知道的
Iterator it=neiPorts.iterator();
while(it.hasNext())
{
allPorts.add((Integer)it.next());
}
allPorts.add(new Integer(routerPort));
activeRouter.add(new Integer(routerId)); //建立这个路由器的时候将这个路由器的端口加入活动的路由器中
/*
Iterator itt=neighborPorts.iterator(); //下面是是初始化isTimeOut
while(itt.hasNext())
{
Integer nei=relation.get((Integer)itt.next());
activeRouter.add(nei);
isTimeOut.put(nei,new Integer(0));
}
*/
//////下面是在刚建立路由器的时候对relation进行初始化
}
synchronized void executeCommand(String command) //不需要单独的Command对象
{
String[] fields;
try
{
//parse the command
fields = command.split("-");//命令进来都有固定的形式,比如X-XX,一共有四个命令
if(fields[0].equals("N")||fields[0].equals("n"))
{
//"N"命令是打印活动的邻居列表
System.out.println("The neighbor of the router is :");
Iterator it=(this.getNeighborPorts()).iterator();
while(it.hasNext())
{
System.out.println(relation.get((Integer)it.next()));
//System.out.println(it.next());
}
}
else if(fields[0].equals("T")||fields[0].equals("t"))
{
//"T"命令是输出路由表
Iterator it=(this.getDestination()).iterator();//destination是一个HashSet类型,故可以直接调用iterator方法
System.out.println("\nThe RoutingTable of is:\nDestination Distance Vector");
while(it.hasNext())
{
Integer inte=(Integer)(it.next());
System.out.print(inte+" ");
System.out.println(RoutingTable.get(inte)); //对应于destination的路由
}
//System.out.println(this.getRoutingTable());
}
else if(fields[0].equals("D")||fields[0].equals("d"))
{
//"D"命令是关闭路由器
System.out.println("Command is shutdowning the router...");
if(activeRouter.contains(new Integer(this.getRouterId())))
{
activeRouter.remove(new Integer(this.getRouterId()));
System.out.println("Command has been executed.");
}
else
{
System.out.println("Warning : The router is not a activity router.");
}
}
else if(fields[0].equals("A")||fields[0].equals("a"))
{
//"A"命令是重启路由器
System.out.println("Command is activiting the router...");
activeRouter.add(new Integer(this.getRouterId()));
System.out.println("Command has been executed.");
}
else
{
System.out.println("Invalid Command..." );
}
}
catch(Exception e)
{
System.out.println("An error occured while executing the command.");
}
}
public static void main(String [] args)
{
String [] getin=null;
BufferedReader readin=null;
try
{
readin=new BufferedReader(new FileReader("E:/HomeWorkTest/MyTest/store.txt"));
}
catch(IOException e)
{
e.printStackTrace();
}
try
{
String line;
line=readin.readLine();
while(line!=null)
{
getin=line.split(" ");
(Router.relation).put(new Integer(getin[1]),new Integer(getin[0]));
(Router.revrelation).put(new Integer(getin[0]),new Integer(getin[1]));
line=readin.readLine();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
/*
String get=null;
String [] getin=null;
System.out.println("Initialize the router,input router Id router port('exit' to quit)");
try
{
while(!flagx)
{
BufferedReader bbr=new BufferedReader(new InputStreamReader(System.in));
get=bbr.readLine();
if(get.equals("exit"))
{
flagx=true;
}
else
{
getin=get.split(" ");
(Router.relation).put(new Integer(getin[1]),new Integer(getin[0])); //将最初的节点信息保存
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
*/
System.out.println("relattion::"+relation);
Packets pks;
String input=null;
String [] fields=null;
HashSet<Integer> neighborports=new HashSet<Integer>();
System.out.println("Input the router here: router ID,myport,port1,port2,...");
System.out.print(" - router ");
Router rt=null;
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
input=br.readLine();
//处理输入
fields=input.split(",");
//将从控制台输入的有关路由器的一些初始信息保存
int routerId=Integer.parseInt(fields[0]);
int routerport=Integer.parseInt(fields[1]);
//Router.relation.put(new Integer(fields[1]),new Integer(fields[0]));
for(int i=2;i<fields.length;i++)
{
neighborports.add(new Integer(fields[i]));
}
rt=new Router(routerId,routerport,neighborports);
//System.out.println("haha neighborports"+neighborports);
Iterator itt=neighborports.iterator();
while(itt.hasNext())//这里是初始化路由表,也就是在刚建立好路由器的时候把邻节点的信息写入
{
Integer storeneiport=new Integer(((Integer)itt.next()).intValue());
Integer store=new Integer(((Router.relation).get(storeneiport)).intValue());
(rt.getRoutingTable()).put(store,store.toString());
rt.fillDestination(store); //在初始化的时候将临街节点加入目的节点中
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
//System.out.println("routingTable"+rt.getRoutingTable());
ReceiveThread r=new ReceiveThread(rt);
//System.out.println("xxxxxxxxxxxxxxxxxxxxxxxx");
SendThread s=new SendThread(rt,rt.getRouterId(),rt.getRouterPort(),rt.getNeighborPorts());//要发送必须做为客户端
//要接受必须作为服务器端端
/*
try
{
r.join();
s.join();
}
catch(Exception ex)
{
ex.printStackTrace();
}*/
String getStrCommand=null;
boolean flag=false;
try
{
while(!flag)
{
System.out.println(" Command List");
System.out.println("-------------------------------------------------");
System.out.println("| -N :Output the neighbors of the router |");
System.out.println("| -T :Output the routingtable of the router |");
System.out.println("| -D :disable the router |");
System.out.println("| -A :able the router |");
System.out.println("|Id-data(input):send the data to the router |");
System.out.println("| Input 'exit' to turn down the programme |");
System.out.println("-------------------------------------------------");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{
getStrCommand=br.readLine();
}
catch(Exception ex)
{
ex.printStackTrace();
}
if(getStrCommand.equals("exit"))
{
flag=true;
}
else
{
String [] newfields = getStrCommand.split("-");
if(newfields.length==1)
{
rt.executeCommand(newfields[0]);
}
else if(newfields.length==2)
{
Integer des=new Integer(newfields[0]);
String inputdata=newfields[1];
rt.fillDataPacket(des,inputdata);
DataFlag=true;
}
else
{
System.out.println("The command invalid...");
}
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -