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

📄 clientprocessor.java

📁 这里是一个构建简单web服务器的部分源代码
💻 JAVA
字号:

import java.io.*;
import java.net.Socket;
import java.net.*;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;


public class ClientProcessor extends Thread {
	private static List pool = new LinkedList();
	private String indexFileName = "index.html";
	private Log log = new Log();
	private int count;

	public ClientProcessor(Socket client,int count) {
		this.count = count;
		synchronized (pool) {
			pool.add(pool.size(), client);
			pool.notifyAll();
		}
	}

	public void run() {
		Socket client;
		while (true) {
			//利用线程池提高效率。
			synchronized (pool) {
				while (pool.isEmpty()) {
					try {
						pool.wait();
					} catch (InterruptedException e) {
						// TODO: handle exception
					}
				}
				client = (Socket) pool.remove(0);
			}

			try {
				String fileName;
				String contentType;
				String ip = client.getInetAddress().toString(); // 客户机IP地址
				client.getInputStream();
				int port = client.getPort(); // 客户机端口号
				

				
				//调用写日志类写日志
				log.writelog(ip.substring(1),port,count);
				
				OutputStream buffer = new BufferedOutputStream(client
						.getOutputStream());
				PrintStream out = new PrintStream(buffer);

				Reader in = new InputStreamReader(new BufferedInputStream(
						client.getInputStream()), "ASCII");

				StringBuffer requestLine = new StringBuffer();			
				int c;
				while (true) {
					c = in.read();
					if (c == '\r' || c == '\n')
						break;
					requestLine.append((char) c);
				}
				String get;
				get = requestLine.toString();

				// 记录请求的日志
				System.out.println(get);

				StringTokenizer st = new StringTokenizer(get);
				String method = st.nextToken();
				String version = "";
				
				if (method.equals("GET")) {
					fileName = st.nextToken();
					if (fileName.endsWith("/"))
						fileName += indexFileName;
						if(fileName.indexOf(';') != -1)
							fileName = fileName.substring(1,fileName.indexOf(';'));
						else 
							fileName = fileName.substring(1);
					contentType = guessContentTypeFromName(fileName);
					if (st.hasMoreTokens()) {
						version = st.nextToken();
					}

					File theFile = new File(fileName);
					
					if (theFile.canRead()) {
						SessionProcessor sp = new SessionProcessor();
						String sid = sp.getsessionid(get);// 获取web浏览器提交的sessionid
						sid = sp.session(sid);// 处理sessionid
						System.out.println(fileName + " requested.");
						DataInputStream fis = new DataInputStream(
								new BufferedInputStream(new FileInputStream(
										theFile)));
						byte[] theData = new byte[(int) theFile.length()];
						fis.readFully(theData);
						fis.close();
						if (version.startsWith("HTTP/1.1")) {
							out.println("HTTP/1.1 200 OK\r\n");
							Date now = new Date();
							out.println("Date: " + now + "\r\n");
							out.println("Server: WebServer/1.1\r\n");
							out.println("Content-length: " + theData.length
									+ "\r\n");
							out.println("Content-type: " + contentType
									+ "\r\n\r\n");
							sendfile(out, theFile); // 发送文件
							out.flush();
						}

						// 发送文件;可能是图片或其他二进制数据
					//	out.println(theData);
						//out.flush();
					} else {
						if (version.startsWith("HTTP/1.1")) {
							out.println("HTTP/1.1 404 File Not Found\r\n");
							Date now = new Date();
							out.println("Date: " + now + "\r\n");
							out.println("Server: WebServer/1.1\r\n");
							out.println("Content-type: text/html\r\n\r\n");
						}
						out.println("<HTML>\r\n");
						out.println("<HEAD><TITLE>File Not Found</TITLE>\r\n");
						out.println("</HEAD>\r\n");
						out.println("<BODY>");
						out.println("<h1>HTTP Error 404: File Not Found</H1>\r\n");
						out.println("</BODY></HTML>/r/n");
						out.println();
					}
				} else if(method.equals("POST")){	
					
					try{
					while((c = in.read()) != -1){
						System.out.print((char)c);
					}
					System.out.println();
					in.close();
					}catch(IOException ex){
						System.err.println(ex);
					}
					
					fileName = st.nextToken();
					if (fileName.endsWith("/"))
						fileName += indexFileName;
						if(fileName.indexOf(';') != -1)
							fileName = fileName.substring(1,fileName.indexOf(';'));
						else 
							fileName = fileName.substring(1);
					contentType = guessContentTypeFromName(fileName);
					if (st.hasMoreTokens()) {
						version = st.nextToken();
					}

					File theFile = new File(fileName);
					
				}
			} catch (IOException ex) {
				// TODO: handle exception
			} finally {
				try {
					client.close();
				} catch (IOException ex) {
				}
			}
		}//while ends.
	}//run ends.

	public static String guessContentTypeFromName(String name) {
		if(name.endsWith(".html") || name.endsWith(".htm")){
			return "text/html";
		}
		else if(name.endsWith(".txt") || name.endsWith(".java")){
			return "text/plain";
		}
		else if(name.endsWith(".gif")){
			return "image/gif";
		}
		else if(name.endsWith(".class")){
			return "application/octet-stream";
		}
		else if(name.endsWith(".jpg") || name.endsWith(".jpeg")){
			return "image/jpeg";
		}
		else return "text/plain";
	}
	
	//把指定文件发送给Web浏览器
	public void sendfile(PrintStream outs, File file) {
		try {
			DataInputStream in = new DataInputStream(new FileInputStream(file));
			int len = (int) file.length();
			byte buf[] = new byte[len];
			in.readFully(buf);// 将文件数据读入buf中
			outs.write(buf, 0, len);
			outs.flush();
			in.close();
		} catch (Exception e) {
			System.out.println("Error retrieving file.");
			System.exit(1);
		}
	}
	
	public void receiveFile(PrintStream ins){
		try{
			File file = new File("/");
		}catch (Exception e){
			System.out.println("Error push file.");
			System.exit(1);
		}
	}
}

⌨️ 快捷键说明

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