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

📄 threadedserver.java

📁 SSD8的练习一
💻 JAVA
字号:
/**
 * @see <code>Client.java</code> and
 * @version 1.0
 *
 * The class is a simple web server class that can respond to the user's request,
 * 		and it can deal with the more than one requests for the same time.
 */

import java.net.*;
import java.util.StringTokenizer;
import java.io.*;

/**
 * The class <code>Handler</code>implements the abstract interface--"Runnable". 
 * 
 */
class Handler implements Runnable{

	private Socket socket;
    
	
	public Handler(Socket s){

		Thread t;
      	socket = s;
       	t = new Thread(this, "Handler Thread");
       	t.start();
	}             
	
	/**
	 * This method is used to implement the thread function.
	 * 
	 *  @param void
	 *  @return void
	 *  @exception <code>Exception</code>
	 */
	public void run() {
		try {
		    
			// Read the request from client
		    BufferedReader inFromClient =
			new BufferedReader(new InputStreamReader(socket.getInputStream()));

		    String requestMessageLine;
		    requestMessageLine = inFromClient.readLine();
		
		    // Process the request
		    StringTokenizer tokenizedLine =
			new StringTokenizer(requestMessageLine);
		
		    if (tokenizedLine.nextToken().equals("GET")) {
			    
				String fileName;
				// Parse URL to retrieve file name
				fileName = tokenizedLine.nextToken();
			    
				if (fileName.startsWith("/") == true )
				    fileName  = "C:\\www\\test\\" + fileName.substring(1);
			    
				File file = new File(fileName);
				int numOfBytes = (int) file.length();
				
				FileInputStream inFile  = new FileInputStream (fileName);
			    
				byte[] fileInBytes = new byte[numOfBytes];
				inFile.read(fileInBytes);
	
				// Get output stream
				DataOutputStream outToClient =
				    new DataOutputStream(socket.getOutputStream());
			    
				// Generate response header
				outToClient.writeBytes("HTTP/1.0 200 Document Follows\r\n");
			    
				if (fileName.endsWith(".jpg"))
				    outToClient.writeBytes("Content-Type: image/jpeg\r\n");
				if (fileName.endsWith(".gif"))
				    outToClient.writeBytes("Content-Type: image/gif\r\n");
			    
				outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
				outToClient.writeBytes("\r\n");
			    
				// Send file content
				outToClient.write(fileInBytes, 0, numOfBytes);
			    
				// Close connection
				socket.close();
				
		    } else { 
		    	
		    	System.out.println("Bad Request Message");
		    }
		} catch (Exception e) {
			
		    System.out.println("Error");
		} // End of catch
		    
	    } // End of run()
}


/**
 * The class <code>ThreadedServer</code> invoks the class <code>Handler</code> to 
 * 		get the multithread method that can control the concurrency event.
 *
 */
class ThreadedServer {
	
	// The connetion port number.
	private static final int serverPort = 6789;
	
	public static void main(String args[]) {
	
		// Create server socket
		ServerSocket listenSocket = null;
		
		try {
			
			listenSocket = new ServerSocket(serverPort);
		} catch (IOException e) {
			
			System.err.println("IO erro when \"ServerSocket(serverPort)\" ");
			e.printStackTrace();
		}
		
		System.out.println("server listening at " + listenSocket);
	
		while (true) {
	
		    // Take a ready connection from the accepted queue
		    Socket connectionSocket = null;
			try {
				
				connectionSocket = listenSocket.accept();
			} catch (IOException e) {
				
				System.err.println("IO erro when \"listenSocket.accept()\" ");
				e.printStackTrace();
			}
			
			
		    System.out.println("receive request from " + connectionSocket);
	
		    // Dispatch a request server
		    new Handler( connectionSocket );
	
		} // End of while (true)
		
    } // End of main
		
	
}



⌨️ 快捷键说明

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