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

📄 webserver.java

📁 java实现web服务器^_^
💻 JAVA
字号:
import java.io.*;
import java.net.*;
import java.util.*;

class WebServer{
     public static void main(String args[])throws Exception
     {
          String requestMessageLine;
          String fileName;
          ServerSocket welcomeSocket = new ServerSocket(8080);
          while(true){
          Socket connectionSocket = welcomeSocket.accept();
         
          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);
               
               File file = new File(fileName);
               
               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/jpg\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);
               //     connectionSocket.close();
               }
		}
     	//	System.out.println("Bad Request Message : "+requestMessageLine);
		//	connectionSocket.close();
          }
}        
                         

⌨️ 快捷键说明

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