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

📄 dxcweb.java

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

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

public class dxcweb {
	public static void main(String argv[]) throws Exception {
		int port=6789;
		ServerSocket listenSocket = null;
		try{
			listenSocket = new ServerSocket(port); 
        	for (;;) {
        		Socket connectionSocket = listenSocket.accept(); // 接受客户机的连接请求
        		new Connection(connectionSocket).start();
        		} 
        	} catch(Exception e){
        		System.out.println(e);
        		}
        	}
	}
  	 class Connection extends Thread {
  		String requestMessageLine;
  		String fileName;
  		Socket connectionclient;
  		public Connection(Socket c1){
  			connectionclient=c1;
  			}
  		public void run() 
  		{ 
  			try {
  				DataOutputStream outToClient = new DataOutputStream(connectionclient.getOutputStream());
  				BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionclient.getInputStream()));
  				requestMessageLine=inFromClient.readLine(); // 读取Web浏览器提交的请求信息
  	        	StringTokenizer tokenizedLine = new StringTokenizer(requestMessageLine);
  	        	System.out.println(requestMessageLine);    
  	        	String s = tokenizedLine.nextToken();
  				System.out.println("Received:"+requestMessageLine); 
  				if (s.equals("GET")) { // 如果是GET请求 
  					fileName = tokenizedLine.nextToken();
  					if (fileName.startsWith("/") == true)
  	        			 fileName = fileName.substring(1);  					
  					System.out.println(fileName+" requested.");
  					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");
  						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); 
  						} 
  					connectionclient.close();
  					}
  				} catch(Exception e)
  				{
  					System.out.println(e);
  					}
  				}
  		}

⌨️ 快捷键说明

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