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

📄 server.java

📁 SSD8练习1答案
💻 JAVA
字号:
/*
 * Created on 2009-3-31
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author liukui
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.StringTokenizer;

public class Server {
	
	/*standard input stream*/
	private static BufferedReader stdIn = 
		new BufferedReader(new InputStreamReader(System.in));
	
	/*standard output stream*/
	private static PrintWriter stdOut = 
		new PrintWriter(System.out,true);
	
	/*the default port number*/
	static final int DEFAULT_PORT = 8000;
	
	/*the port number request by the client*/
	private int port = 0;
	
	/*a identifier shows the request from the client is legal*/
	static final int SUCCESS = 200;
	
	/*a identifier shows the request from the client is illegal*/
	static final int FAILED = 400;
	
	/*a variable shows the request is legal or not*/
	static String responseState = 200 + " OK";
	
	/*a client socket*/
	static Socket client;
	
	/*a server socket*/
	static ServerSocket server;
	
	/*the server's name*/
	static String hostname = null;
	
	/*the response time */
	static Date responseTime;
	
	/*the code name of the erro when the client send a bad request*/
	static String ERRO = "";
	
	/**
	 * the Server constructor and it creat a socket object for connecting the client
	 */
	public Server(String h) {
		hostname = h;
		try {
			server = new ServerSocket(DEFAULT_PORT);
			stdOut.println(hostname + "Server Running...");
			stdOut.println("The client's request should be \"GET URL protocol\"," +
					"\nor the server can not identify the command!");
			stdOut.flush();
			client = server.accept();
		} catch (Exception e) {
			e.toString();
		}
	}
	
	/**
	 * @param when the client request the server's service, this method response it and 
	 * get the information which will be send to the client
	 */
	
	public void response(String fileType,long fileLength,
			FileReader file) throws Exception {
		
		DataOutputStream outToClient = 
			new DataOutputStream(client.getOutputStream());
		String sendToClient = null;	//the information which will be send to the client												
		String content = null;//the content of the file which the client request
		
		sendToClient = "HTTP/1.0 " + responseState + "\n"
						+"Server: " + hostname + "\n"
						+"Date: " + responseTime + "\n"
						+"Content-Type: " + fileType + "\n"
						+"Content-Length: " + fileLength + "\n"
						+"Expires: " + new Date() + "\n"//the time the response end
						+ERRO+"Via: " + hostname + " "+DEFAULT_PORT+"\n"
						+"Connection: close\n\n";
		
		//when the client request the text or html file,get the file's content
		if(fileType == "text/html" || fileType == "txt") {
			int i = 0;
			while(i<fileLength) {
				content += (char)file.read();
				i++;
			}
			file.close();
		}
		
		//send the information to the client
		sendToClient += content;
		outToClient.writeBytes(sendToClient);
	}
	
	public static void main(String[] args) throws Exception {
		
		String fileType = null;//
		String newUrl = null;
		long fileLength = 0;
		boolean containFile = false;
		FileReader file = null;
		String protocol = null;
		
		if(args.length != 1) {
			stdOut.println("error");
		}
		else {
			Server s = new Server(args[0]);
			
			try {
				BufferedReader inFromClient =
					new BufferedReader(new InputStreamReader(client.getInputStream()));
				
				//the command from the client
				String command = inFromClient.readLine();
				StringTokenizer request= new StringTokenizer(command);
				
				command = request.nextToken();
				
				//initialize the respondent information 
				responseState = FAILED + " Bad Request";
				responseTime = new  Date();
				ERRO = "X_" + hostname +"ERR_INVALID_REQ 0\n";
				
				//analyse the command get from the client
				if(command.equals("GET")) {
					
					String url = "";//the path of the file which the client request
					if(request.countTokens() != 2) {
						url = "";
					} else {
						url = request.nextToken();
						protocol = request.nextToken();
					}
					if(url.startsWith("/")) {
						request = new StringTokenizer(url,"/");
						newUrl = request.nextToken();
						while(request.hasMoreTokens()) {
								newUrl = newUrl + "\\" + request.nextToken();
					}
					if(newUrl.endsWith(".html")) {
						fileType = "text/html";
						responseTime = new  Date();
						containFile = true;
					} else if(newUrl.endsWith(".jpg")) {
						fileType = "image/jpeg";
						responseTime = new  Date();
						containFile = true;
					} else if(newUrl.endsWith(".gif")) {
						fileType = "image/gif";
						responseTime = new  Date();
						containFile = true;
					} else if(newUrl.endsWith(".txt")) {
						fileType = "txt";
						responseTime = new  Date();
						containFile = true;
					} 
				}
					
					url = hostname + "\\" + newUrl;
					try {
						File f = new File(newUrl);
						fileLength = f.length();
						file = new FileReader(newUrl);
						
						if(containFile == true) {
							responseState = SUCCESS + " OK";
							responseTime = new  Date();
							ERRO = "";
						}
					} catch(Exception e) {
							stdOut.println("The file is not existent!");
							stdOut.flush();
					}
				} 
				s.response(fileType,fileLength,file);
				client.close();
				server.close();
			} catch (Exception e) {
				e.toString();
			}
		}
	}
}

⌨️ 快捷键说明

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