📄 router.java
字号:
/* File: Router.java * * This file contains the code for the class Router, * which represents a router in the network. Each router * maintains a Routing Table, Distance Vector and a list of * incoming neighbors to which it has to send the distance vector * * It also spawns two threads for listening the commands from the * Command program and the distance vectors from other Routers */import java.net.*;import java.util.*;import java.io.*;class Router { // the id of this router int id; // the IP address of this router InetAddress ipAddress; // the port on which the commands from Command are received int commandPort; // the port on which the distance vectors from the neighbors are received int routerPort; // number of distance vector packets received int packets; // the distance vector. each entry is of the form (a=b) where b is the // minimum known distance to router a HashMap dv; // the routing table RoutingTable rt; // information about the other routers' IP addresses and router ports RouterLocation rl; // the set of incoming neighbors HashSet inNeighbors; /** * Constructor * * @rlf: Router Location File * @tcf: Topology Configuration File * @id: The id of this Router * * Use: To read the configuration files and initialize the routing table of * this router */ public Router(String rlf, String tcf, int id) { // Initialize the RouterLocation rl = new RouterLocation(rlf); if (rl.contains(id) == false) { System.out.println("Router with ID " + id + " not found in file " + rlf); System.out.println("Quitting."); System.exit(1); } this.id = id; ipAddress = rl.getIp(id); commandPort = rl.getCommandPort(id); routerPort = rl.getRouterPort(id); packets = 0; // Initialize the routing table rt = new RoutingTable(id, tcf); inNeighbors = rt.getInNeighbors(); dv = rt.getDistanceVector(); // Spawn threads for listening on the command and router ports RouterThread r = new RouterThread(this, routerPort,Thread.currentThread().getName()); CommandThread c = new CommandThread(this, commandPort,Thread.currentThread().getName()); try { r.join(); c.join(); } catch (InterruptedException ie) { } } public void printDV(HashMap dv){ Map map = dv; String result = ""; for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object val = entry.getValue(); result += "-"; result += "( " +val+ " )"; result += " -> Node (Port "+key+") \n"; } System.out.println(result); } /** * Method Name: processDV * * @p: The packet containing the distance vector * * Use: To update the routing table when a distance vector is received from * the neihbor */ synchronized void processDV(Packet p) { packets++; // get the distance vector from the packet HashMap newdv = p.getDV(); // get the id of the neighbor from which the distance vector is received int routerId = p.getRouterId(); System.out.println("\nMessage received at Node (Port "+Thread.currentThread().getName()+") from Node (Port "+routerId+")"); //System.out.println(rt); HashMap dv = rt.getDistanceVector(); System.out.println("The Node(Port "+Thread.currentThread().getName()+") Routing Table"); printDV(dv); // update the routing table if (rt.updateTable(newdv, routerId) == false) { System.out.println("Invalid Distance Vector received from Router " + routerId); } else { //System.out.println("The Node("+Thread.currentThread().getName()+") new Routing Table is: "); /*System.out.println(rt);*/ HashMap dvnew = rt.getDistanceVector(); // if there is no change in the distance vector, do not send it to // the neighbors if (dvnew.equals(dv)) { System.out.println("There is no change in the Distance Vector"); return; } // if the distance vector changes, send it to the incoming neighbors else { dv = new HashMap(dvnew); System.out.println("The Node(Port "+Thread.currentThread().getName()+") new Routing Table"); printDV(dvnew); Iterator i = inNeighbors.iterator(); while (i.hasNext()) { int r = ((Integer) i.next()).intValue(); try { Socket s = new Socket(rl.getIp(r), rl.getRouterPort(r)); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); //System.out.println("Sending the Distance Vector " + dvnew + " to Router " + r); System.out.println("Message sent from Node (Port "+Thread.currentThread().getName()+") to Node (Port "+r+")"); if (dvnew != null) oos.writeObject(new Packet(id, dvnew)); oos.close(); s.close(); } catch (IOException e) { System.out.println("An I/O error occured while "+Thread.currentThread().getName()+" sending the Distance Vector to Router " + r); continue; } } } } return; } /* * Method Name: executeCommand * * @command: the command sent by the Command program * * Use: To execute the command sent by the Command program */ synchronized String executeCommand(String command) { String[] fields; try { // parse the command fields = command.split(":"); System.out.println("\nReceived " + command + " from COMMAND"); if (fields[0].equals("addRouter")) { return ("true"); } else if (fields[0].equals("deleteRouter")) { boolean flag = false; int id = Integer.parseInt(fields[1]); if (id == this.id) { return ("Success"); } // if the node is one of the neighbors, the distance vector has // to be recalculated if (rt.getNeighbors().contains(new Integer(id))) flag = true; if (rt.deleteNode(id) == false) { return ("Trying to delete an unidentified router"); } else { // recalculate the distance vector if (flag == true) { dv = rt.getDistanceVector(); } // if the neighbor is also an incoming neighbor, delete it // from that list inNeighbors.remove(new Integer(id)); return ("Success"); } } // update the weight of the link to an outgoing neighbor else if (fields[0].equals("updateto")) { int id = Integer.parseInt(fields[1]); int weight; // represent infinity by an integer 10000 if (fields[2].equals("inf")) { weight = 10000; } else { weight = Integer.parseInt(fields[2]); } if (rt.updateWeight(id, weight) == false) { return ("Invalid update"); } else { // recalculate the distance vector dv = rt.getDistanceVector(); return ("Success"); } } // update the weight of the link to an incoming neihbor else if (fields[0].equals("updatefrom")) { int id = Integer.parseInt(fields[1]); Integer ID = new Integer(id); // if the link is deleted, remove it from the list if (fields[2].equals("inf")) { if (inNeighbors.contains(ID)) { inNeighbors.remove(ID); } } // else, if the neighbor is not already in the list, add it else { if (inNeighbors.contains(ID) == false) { inNeighbors.add(ID); } } return ("Success"); } else if (fields[0].equals("packets")) { String result = "" + packets; packets = 0; return (result); } else if (fields[0].equals("route")) { int id = Integer.parseInt(fields[1]); dv = rt.getDistanceVector(); System.out.println("The Distance Vector is " + dv); Integer ID = new Integer(id); if ((dv == null) || (dv.containsKey(ID) == false)) { return ("error"); } else if (((Integer) dv.get(ID)).intValue() == 10000) { return ("inf"); } else { return (rt.getNextHop(ID, (Integer) dv.get(ID))); } } else if (fields[0].equals("display")) { return (rt.toString()); } else if (fields[0].equals("step")) { boolean error = false; dv = rt.getDistanceVector(); // get the list of all incoming neighbors Iterator i = inNeighbors.iterator(); while (i.hasNext()) { try { int routerId = ((Integer) i.next()).intValue(); if (dv != null) { Socket s = new Socket(rl.getIp(routerId), rl .getRouterPort(routerId)); ObjectOutputStream oos = new ObjectOutputStream(s .getOutputStream()); /*System.out.println("Sending the Distance Vector " + dv + "to Router " + routerId);*/ System.out.println("Message sent from Node (Port "+Thread.currentThread().getName()+") to Node (Port "+routerId+")"); oos.writeObject(new Packet(id, dv)); oos.close(); s.close(); } else { System.out.println("Distance Vector empty"); } } catch (Exception e) { error = true; } } if (error == true) { return ("Distance Vector could not be sent to some some neighbors"); } else { return ("Successfully sent the Distance Vector to all the neighbors"); } } else { return ("Invalid Command: " + fields[0]); } } catch (Exception e) { return ("And error occured while executing the command. Either the arguments are bad or the error occured while communicating with other ROUTERs"); } } /* * Method Name: main * * @args: the command line arguments * * Use: To start the execution of the Router */ public static void main(String[] args) { String rlf = "rlf.txt"; String tcf = "tcf.txt"; int id = -1; ; if ((args.length == 0) || ((args.length == 1) && (args[0].equals("-h")))) { System.out.println("Usage: java Router <options> router_id"); System.out.println("where possible options include:"); System.out.println(" -h : Print a synopsis of options"); System.out.println(" -f <tcf> : Override the default Topology Configuration File (tcf.txt)"); System.out.println(" -l <rlf> : Overrode the default Router Location File (rlf.txt)"); System.exit(1); } else { for (int i = 0; i < (args.length - 1); i++) { if (args[i].equals("-h")) { System.out .println("Usage: java Router <options> router_id"); System.out.println("where possible options include:"); System.out .println(" -h : Print a synopsis of options"); System.out .println(" -f <tcf> : Override the default Topology Configuration File (tcf.txt)"); System.out .println(" -l <rlf> : Override the default Router Location File (rlf.txt)"); } else if (args[i].equals("-f")) { if (i == (args.length - 2)) { System.out.println("Please specify the value for option '-f'"); System.exit(1); } else { tcf = args[i + 1]; i++; } } else if (args[i].equals("-l")) { if (i == (args.length - 2)) { System.out.println("Please specify the value for option '-l'"); System.exit(1); } else { rlf = args[i + 1]; i++; } } else { System.out.println("Invalid argument: " + args[i]); System.exit(1); } } try { id = Integer.parseInt(args[args.length - 1]); } catch (NumberFormatException nfe) { System.out.println("Invalid router_id " + args[args.length - 1]); System.exit(1); } Router r = new Router(rlf, tcf, id); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -