Java簡單的Web服務器Socket實現
一、實現思路
1、使用 ServerSocket 監聽某一端口,然後等待連接獲取 Socket對象。
2、創建一個類 HttpServer 繼承 java.lang.Thread 類,重寫 run()方法,執行瀏覽器請求。
3、獲得瀏覽器請求,解析資源文件路徑。
4、讀取資源文件,響應給瀏覽器。
原創在這 我稍微改進了一下
https://blog.csdn.net/HaHa_Sir/article/details/80594982
二、代碼實現
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class WebServer {
//
public void startServer(int port){
try {
@SuppressWarnings("resource")
ServerSocket serverSocket = new ServerSocket(port);
while(true){
//服務器套接字
Socket socket = serverSocket.accept();
new HttpServer(socket).start(); {
};
}
} catch (IOException e) {
e.printStackTrace();
}
}
//啓動
public static void main(String[] args) {
new WebServer().startServer(8000);
}
}
以下是實現的方法
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
/**
* @description: 使用socket 實現 web服務器 --- 具體執行讀寫操作的。
*
*/
public class HttpServer extends Thread {
/**
* web資源根路徑
*/
/**
* 輸入流對象,讀取瀏覽器請求
*/
private InputStream input;
/**
* 輸出流對象,響應內容給瀏覽器
*/
private OutputStream out;
/**
* @description:初始化socket對象,獲取對應 輸入,輸出流
* @param socket
*/
public HttpServer(Socket socket) {
try {
input = socket.getInputStream();
out = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 多線程方法調用
*/
@Override
public void run() {
String filePath = read();
response(filePath);
}
/**
* @description: 讀取資源文件,響應給瀏覽器。
* @param:@param filePath 資源文件路徑
*
*
*/
private void response(String filePath) {
//獲得項目下的路徑
String path = System.getProperty("user.dir");
File file = new File(path + filePath);
if (!filePath.equals("/")) {
if (file.exists()) {
// 1、資源存在,讀取資源
try {
//做個判斷是否爲空
BufferedReader reader = new BufferedReader(new FileReader(file));
System.out.println("reader" + reader);
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\r\n");
}
StringBuffer result = new StringBuffer();
result.append("HTTP /1.1 200 ok \r\n");
result.append("Content-Type:text/html \r\n");
result.append("Content-Length:" + file.length() + "\r\n");
result.append("\r\n" + sb.toString());
//System.out.println("result=="+result);
out.write(result.toString().getBytes());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
// 2、資源不存在,提示 file not found
StringBuffer error = new StringBuffer();
error.append("HTTP /1.1 400 file not found \r\n");
error.append("Content-Type:text/html \r\n");
error.append("Content-Length:20 \r\n").append("\r\n");
error.append("<h1 >File Not Found..</h1>");
try {
out.write(error.toString().getBytes());
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}else {
//默認界面
StringBuffer error = new StringBuffer();
error.append("HTTP /1.1 200 hello word \r\n");
error.append("Content-Type:text/html \r\n");
error.append("Content-Length:20 \r\n").append("\r\n");
error.append("<h1 >hello word</h1>");
try {
out.write(error.toString().getBytes());
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @description:解析資源文件路徑
* @example: GET /index.html HTTP/1.1
*
*
*/
private String read() {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
try {
// 讀取請求頭, 如:GET /index.html HTTP/1.1
String readLine = reader.readLine();
String[] split = readLine.split(" ");
if (split.length != 3) {
return null;
}
//System.out.println(readLine);
return split[1];
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
創建一個index.html 放在根目錄下
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Hello World! this is my webserver!</h1>
</body>