您的位置:首頁技術文章
文章詳情頁

Java 實現簡單靜態資源Web服務器的示例

瀏覽:29日期:2022-08-21 10:38:11

需求

有時候我們想快速通過http訪問本地的一些資源,但是安裝一些web服務器又很費時和浪費資源,而且也不是長期使用的。

這時候我們可以啟動一個小型的java服務器,快速實現一個http的靜態資源web服務器。

難點

其實沒什么難點,主要是注意請求頭和返回頭的處理。然后將請求的文件以流的方式讀入返回outputstream即可。

代碼

直接上代碼吧~

import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths; public class ResourceWebServer { private static final int SERVER_PORT = 8888; private static final int MAX_CONNECTION_LENGTH = 1; public static void main(String[] args) throws IOException {log('======服務器啟動=====');ResourceWebServer server = new ResourceWebServer();server.startServer(); } public void startServer() throws IOException {ServerSocket serverSocket = new ServerSocket(SERVER_PORT, MAX_CONNECTION_LENGTH, InetAddress.getByName('localhost')); log('======準備接收請求=====');while (true) { Socket socket = serverSocket.accept(); try (InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream()) { String requestUri = getRequestUri(inputStream);log('請求文件:' + requestUri); writeHeaders(outputStream); Path path = Paths.get(getClass().getClassLoader().getResource(requestUri.substring(1)).toURI());Files.copy(path, outputStream); } catch (Exception e) {log('發生錯誤啦!');e.printStackTrace(); }} } private void writeHeaders(OutputStream outputStream) throws IOException {//必須包含返回頭,否則瀏覽器不識別outputStream.write('HTTP/1.1 200 OKrn'.getBytes());//一個rn代表換行添加新的頭,2次rn代表頭結束outputStream.write('Content-Type: text/htmlrnrn'.getBytes()); } private String getRequestUri(InputStream inputStream) throws IOException {StringBuilder stringBuilder = new StringBuilder(2048);byte[] buffer = new byte[2048];int size = inputStream.read(buffer); for (int i = 0; i < size; i++) { stringBuilder.append((char) buffer[i]);} String requestUri = stringBuilder.toString();//此時的uri還包含了請求頭等信息,需要去掉//GET /index.html HTTP/1.1...int index1, index2;index1 = requestUri.indexOf(' ');if (index1 != -1) { index2 = requestUri.indexOf(' ', index1 + 1); if (index2 > index1) {return requestUri.substring(index1 + 1, index2); }}return ''; } private static void log(Object object) {System.out.println(object); }}

接下來,就可以在resource文件下放入靜態資源啦,比如放一個index.html

然后啟動,打開瀏覽器輸入http://localhost:8888/index.html就能看到結果了!

以上就是Java 實現簡單靜態資源Web服務器的示例的詳細內容,更多關于java 實現web服務器的資料請關注好吧啦網其它相關文章!

標簽: Java
相關文章:
国产综合久久一区二区三区