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

📄 commandthread.java

📁 使用Java语言编写模拟路由器程序
💻 JAVA
字号:
/* File: CommandThread.java * * Author: Venkata Sastry Malladi * * This file contains the code for the class CommandThread, * which represents the thread spawned by each Router to  * listen for commands sent by the Command * * Preferred Editor: emacs */import java.io.*;import java.net.*;class CommandThread extends Thread {	// the instance of the router that spawned this thread	Router r;	// the port on which the thread listens for commands from the Command	// program	int port;	/*	 * Constructor	 * 	 * @r: the instance of the router that spawned this thread @port: port	 * number	 */	public CommandThread(Router r, int port,String threadName) {		// create the 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() {		// socket to listen on the command port		ServerSocket l = null;		// socket to represent the accepted connection		Socket t;		// the input and output streams associated with the connection		ObjectOutputStream oos;		ObjectInputStream ois;		try {			// listen on the command port			l = new ServerSocket(port);			System.out.println("Router "+Thread.currentThread().getName()+" Command: Listening for commands on port "					+ port);		} catch (Exception e) {			System.out					.println("Router "+Thread.currentThread().getName()+" Command: 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()+" Command: An I/O error occured while accepting a connection");				continue;			}			try {				// open the streams				oos = new ObjectOutputStream(t.getOutputStream());				ois = new ObjectInputStream(t.getInputStream());				// read the command				String in = (String) ois.readObject();				// execute the command and send the response				String out = r.executeCommand(in);				oos.writeObject(out);				// close the streams and the connection				ois.close();				oos.close();				t.close();			} catch (Exception e) {				System.out						.println("Router "+Thread.currentThread().getName()+" Command: An I/O error occured while communicating with COMMAND");				continue;			}		}	}}

⌨️ 快捷键说明

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