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

📄 httpssession.java

📁 精通Java网络编程代码全部
💻 JAVA
字号:
import java.io.*;
import java.net.*;
import java.util.*;

class HTTPSSession implements Runnable {
	private static final String CRLF = "\r\n";
	Socket clientSocket;//客户端套接字
	private DataInputStream in;
	private DataOutputStream out;
	private String fileAsked;
	
	HTTPSSession(Socket sckIn) throws Exception {
		this.clientSocket = sckIn;
		in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
		out = new DataOutputStream(new BufferedOutputStream(clientSocket.getOutputStream()));
	}
	
	public void run() {
		try {
			//处理所有的请求
			handlerRequest();
		} catch(Exception e) {
			System.out.println("Error in HTTPSSession:");
			e.printStackTrace();
		} finally {
			try {
				out.close();//关闭输出流
				clientSocket.close();
			} catch ( Exception e) {
				System.out.println("Error in HTTPSSession:");
				e.printStackTrace();
			}
		}
	}
	
	private void handlerRequest() throws IOException {
		int pos;
		String requestLine = in.readLine(); // 读取第一行
		System.out.println(requestLine);
		StringTokenizer tokens = new StringTokenizer(requestLine);
		String reqType = tokens.nextToken();
		// 只对GET来说
		if(reqType.equalsIgnoreCase("GET")) {
			String fileName = tokens.nextToken();
			pos = fileName.indexOf(":");
			if(pos == -1) { // maybe => "GET / HTTP/1.1"
				fileAsked = fileName; 
			} else { // maybe => "GET http://localhost HTTP/1.1
				fileAsked = new StringBuffer().append(fileName.substring(pos+3)).toString();
			}
			pos = fileAsked.indexOf("/");
			if(pos == -1) {
				fileAsked = "/"; // 发生在 => "GET http://localhost HTTP/1.1
			} else {
				fileAsked = new StringBuffer().append(fileAsked.substring(pos))
					.toString(); // 在没有主机名字的情况下,保存路径
			}
			// fileAsked handler
			fileAskedHandler();
		} else {
			// 不支持的情况
			sendError(501, "Your request: " + reqType + " haven't implemented yet");
		}
	}
	
	private void fileAskedHandler() throws IOException {
		String fileSent = "";
		System.out.println("File Asked " + fileSent );
		if(fileAsked.equals("/")) {
			fileSent = "index.html"; //  转换符号 / 到index.html页面
		} else if(fileAsked.startsWith("/")) {
			fileSent = fileAsked.substring(1); // 将/mama.html转换为mama.html
		}
		if(fileSent.endsWith("/")) {
			fileSent += "index.html"; // 将/dada/ 转换为 /dada/index.html 
		}
		File fileToSent = new File("wwwroot/" + fileSent);  
		System.out.println("File To sent " + fileToSent );
		if( !fileToSent.exists() || !fileToSent.canRead()  // 确定文件可读
			|| fileToSent.isDirectory()  //这不可能
			|| (fileSent.indexOf("..") > -1 ) ) { 
			// error error
			sendError(404, "File of " + fileSent + " can't be found or we got invalid path" );
			return;
		}
		int posMIME = fileSent.lastIndexOf("."); // 获取MIME类型
		String contentType = "text/plain"; // 默认的方法
		if(posMIME != -1) {
			String fileExtention = fileSent.substring(posMIME+1);
			if(fileExtention.equalsIgnoreCase("htm") || fileExtention.equalsIgnoreCase("html")) {
				contentType = "text/html; charset=iso-8859-1";
			} else if(fileExtention.equalsIgnoreCase("jpg") || fileExtention.equalsIgnoreCase("jpeg")) {
				contentType = "image/jpeg";
			} else if(fileExtention.equalsIgnoreCase("gif")) {
				contentType = "image/gif";
			} else if(fileExtention.equalsIgnoreCase("png")) {
				contentType = "image/png";
			} else if(fileExtention.equalsIgnoreCase("pdf")) {
				contentType = "application/pdf";
			} else if(fileExtention.equalsIgnoreCase("xml")) {
				contentType = "text/xml";
			} else if(fileExtention.equalsIgnoreCase("css")) {
				contentType = "text/css";
			} else if(fileExtention.equalsIgnoreCase("ps") || fileExtention.equalsIgnoreCase("eps")) {
				contentType = "application/postscript";
			}
		}
		sendHeader(200, contentType, fileToSent.length());
		endHeader();
		BufferedInputStream fileContent = new BufferedInputStream(new FileInputStream(fileToSent));
		byte[] fileBuffer = new byte[4500];
		int flag = fileContent.read(fileBuffer);
		while(flag != -1) { // read untill we reach EOF
			out.write(fileBuffer, 0, flag);
			flag = fileContent.read(fileBuffer);
		}
		out.flush(); //广播信息
		fileContent.close(); // 文件要关闭
	}
	
	private void sendHeader(int status, String mimeType, long contentLong) throws IOException {
		String toSend;
		sendHeader(status); //发送头文件
		toSend = "Content-Length: " + String.valueOf(contentLong) + CRLF;
		out.write(toSend.getBytes(), 0, toSend.length());
		toSend = "Content-Type: " + mimeType + CRLF;
		out.write(toSend.getBytes(), 0, toSend.length());
	}
	/**
	*发送头文件信息
	*/
	private String sendHeader(int status) throws IOException {
		String message, toSend;
		switch(status) {
		case 200:message = "200 OK"; break;
		case 202:message = "202 Accepted"; break;
		case 300:message = "300 Ambiguous"; break;
		case 301:message = "301 Moved Permanently"; break;
		case 400:message = "400 Bad Request"; break;
		case 401:message = "401 Denied"; break;
		case 403:message = "403 Forbidden"; break;
		case 404:message = "404 Not Found"; break;
		case 405:message = "405 Bad Method"; break;
		case 413:message = "413 Request Entity Too Large"; break;
		case 415:message = "415 Unsupported Media"; break;
		case 501:message = "501 Not Implemented"; break;
		case 502:message = "502 Bad Gateway"; break;
		case 504:message = "504 Gateway Timeout"; break;
		case 505:message = "505 HTTP Version Not Supported"; break;
		default: message = "500 Internal Server Error";
		}
		toSend = "HTTP/1.1 " + message + CRLF; // 发送版本信息
		out.write(toSend.getBytes(), 0, toSend.length());
		toSend = "Server: HTTPSSrvr/0.1.A" + CRLF; // 给出身份信息
		out.write(toSend.getBytes(), 0, toSend.length());
		if(status == 501) {
			toSend = "Allow: GET" + CRLF;
			out.write(toSend.getBytes(), 0, toSend.length());
		}
		toSend = "Cache-Control: no-cache, must-revalidate"; 
		out.write(toSend.getBytes(), 0, toSend.length());
		toSend = "Connection: close";
		out.write(toSend.getBytes(), 0, toSend.length());
		return message;
	}
		private void endHeader() throws IOException {
		out.write(CRLF.getBytes(), 0, CRLF.length());
	}
	
	private void sendError(int status, String message) throws IOException {
		String statusMSG = sendHeader(status);
		String srvrMSG = "<HTML><HEAD><TITLE>" + statusMSG + "</TITLE></HEAD>\r<BODY>\r"
			+ "<P><TT>HTTP " + statusMSG + "</TT></P>\r"
			+ "<P>Reason : <B>" + message + "</B></P>\r"
			+ "<P>HTTPSSrvr v 0.1.Alpha</P>\r"
			+ "</BODY></HTML>";
		String toSend;
		toSend = "Content-Length: " + String.valueOf( srvrMSG.length() ) + CRLF;
		out.write(toSend.getBytes(), 0, toSend.length());
		toSend = "Content-Type: text/html; charset=iso-8859-1" + CRLF;
		out.write(toSend.getBytes(), 0, toSend.length());
		endHeader();
		out.write(srvrMSG.getBytes(), 0, srvrMSG.length());
		out.flush();
	}
	
	
}

⌨️ 快捷键说明

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