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

📄 simpleweb.java

📁 实现http的多项功能
💻 JAVA
字号:

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

public class simpleweb {
	public static void main(String argv[]) throws Exception {
         String requestMessageLine;
         String fileName;
         ServerSocket listenSocket = null;
         listenSocket = new ServerSocket(6789);  
    	 while(true) {                		 
        	 Socket connectionSocket = listenSocket.accept();
        	 System.out.println("New connection accepted " +
        			 connectionSocket.getInetAddress() +
        			 ":" + connectionSocket.getPort());
        	 BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
        	 DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());       		 
        	 requestMessageLine = inFromClient.readLine();
        	 StringTokenizer tokenizedLine = new StringTokenizer(requestMessageLine);
        	 System.out.println(requestMessageLine);       
        	 if (tokenizedLine.nextToken().equals("GET")){
        		 fileName = tokenizedLine.nextToken();
        		 if (fileName.startsWith("/") == true)
        			 fileName = fileName.substring(1);
        		 System.out.println(fileName);
        		 File file = new File(fileName);
        		 if (file.exists()) {
        			 int numOfBytes = (int) file.length();
        			 FileInputStream inFile = new FileInputStream(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("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");
        			 outToClient.write(fileInBytes,0,numOfBytes);
        			 }
        		 else { // 文件不存在时         	   
        			 String notfound="<html><head><title>Not 	Found</title></head><body><h1>Error 404-file not 	found</h1></body></html>"; 
        	         outToClient.writeBytes("HTTP/1.0 404 no found"); 
        	         outToClient.writeBytes("Content_Type:text/html"); 
        	         outToClient.writeBytes("Content_Length:"+notfound.length()+2); 
        	         outToClient.writeBytes(""); 
        	         outToClient.writeBytes(notfound); 
        	         }
                	 connectionSocket.close();
                	 }
        	 else System.out.println("Bad Request Message"); 
        	 }
    	 }
	}

	
	

⌨️ 快捷键说明

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