日期:2014-05-20 浏览次数:20792 次
import java.io.*; import java.net.*; import java.util.*; public class Server { public static void main(String[] args) throws Exception { String requestMessageLine; String fileName; ServerSocket listenSocket = new ServerSocket(8000); Socket connectSocket = listenSocket.accept(); BufferedReader inFormClient = new BufferedReader(new InputStreamReader( connectSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectSocket.getOutputStream()); requestMessageLine = inFormClient.readLine(); StringTokenizer tokenizedLine = new StringTokenizer(requestMessageLine); InputStream is = connectSocket.getInputStream(); OutputStream os = connectSocket.getOutputStream(); PrintWriter pw = new PrintWriter(os); while (true) { if (tokenizedLine.nextToken().equals("GET")) { fileName = tokenizedLine.nextToken(); if (fileName.startsWith("/") == true) { fileName = fileName.substring(1); } String filePath = new String("C:\\www\\"); File file = new File(filePath + fileName); int numOfBytes = (int) file.length(); try { FileInputStream inFile = new FileInputStream(filePath + fileName); byte[] fileInBytes = new byte[numOfBytes]; inFile.read(fileInBytes); outToClient.writeBytes("HTTP/1.0 200 Document Follows\r\n"); if (fileName.endsWith(".jpg")) { outToClient.writeBytes("Conten-Type: image/jpeg\r\n"); } else if (fileName.endsWith(".gif")) { outToClient.writeBytes("Conten-Type: image/gif\r\n"); } else if (fileName.endsWith(".html") || fileName.endsWith(".htm")) { outToClient.writeBytes("Conten-Type: text/html\r\n"); // System.out.println(outToClient.toString()); } outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n"); outToClient.writeBytes("\r\n"); outToClient.write(fileInBytes, 0, numOfBytes); connectSocket.close(); } catch (FileNotFoundException e) { outToClient.writeBytes("HTTP/1.0 200 Document Follows\r\n"); pw.print("ContentType: text/html\r\n"); pw.print("\r\n"); pw.print("<body>"); pw.println("Your request: " + fileName + " is not found!"); pw.print("</body>"); pw.close(); is.close(); } catch (NoSuchElementException ee) { outToClient.writeBytes("HTTP/1.0 200 Document Follows\r\n"); pw.print("ContentType: text/html\r\n"); pw.print("\r\n"); pw.print("<body>"); pw.println("No support for other request except GET!"); pw.print("</body>"); pw.close(); is.close(); } } } } }