⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 routerthread.java

📁 使用Java语言编写模拟路由器程序
💻 JAVA
字号:
/* File: RouterThread.java *  * This file contains the code for the class RouterThread, * which represents the thread spawned by each Router to * listen for Distance Vectors from other Routers */import java.io.*;import java.net.*;class RouterThread extends Thread {	// The Router that spawned this thread	Router r;	// The port on which this thread listens for Distance Vector packets	int port;	/*	 * Constructor	 * 	 * @r: the instance of the Router that spawned this thread @port: the port	 * number	 */	public RouterThread(Router r, int port,String threadName) {		// create a new thread		super(threadName);		this.r = r;		this.port = port;		// start the thread		start();	}	/*	 * Method Name: run	 * 	 * Use: To start the execution of the thread	 */	public void run() {		// The socket used to listen on the port		ServerSocket l = null;		// The socket for representing accepted connection		Socket t;		// The input stream associated with the connection		ObjectInputStream ois;		try {			// listen on the port			l = new ServerSocket(port);			System.out					.println("Router "+Thread.currentThread().getName()+": Listening for neighbors' updates on port "							+ port);		} catch (Exception e) {			System.out					.println("Router "+Thread.currentThread().getName()+": Unable to open a listening socket on port: "							+ port);			System.out.println("Quitting.");			System.exit(1);		}		while (true) {			try {				// accept a connection				t = l.accept();			} catch (Exception e) {				System.out.println("Router "+Thread.currentThread().getName()+" :"+e.getMessage());				e.printStackTrace();				System.out						.println("Router "+Thread.currentThread().getName()+": An I/O error occired while accepting a connection");				continue;			}			try {				// open the input stream				ois = new ObjectInputStream(t.getInputStream());				// read the distance vector packet				Packet p = (Packet) ois.readObject();				// process the packet				r.processDV(p);				// close the stream and the connection				ois.close();				t.close();			} catch (Exception e) {				System.out.println("Router "+Thread.currentThread().getName()+" :"+e.getMessage());				e.printStackTrace();				System.out.println("Router "+Thread.currentThread().getName()+": An I/O error occured while communicating");				continue;			}		}	}}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -