Java 實(shí)現(xiàn)簡單靜態(tài)資源Web服務(wù)器的示例
需求
有時(shí)候我們想快速通過http訪問本地的一些資源,但是安裝一些web服務(wù)器又很費(fèi)時(shí)和浪費(fèi)資源,而且也不是長期使用的。
這時(shí)候我們可以啟動(dòng)一個(gè)小型的java服務(wù)器,快速實(shí)現(xiàn)一個(gè)http的靜態(tài)資源web服務(wù)器。
難點(diǎn)
其實(shí)沒什么難點(diǎn),主要是注意請求頭和返回頭的處理。然后將請求的文件以流的方式讀入返回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('======服務(wù)器啟動(dòng)=====');ResourceWebServer server = new ResourceWebServer();server.startServer(); } public void startServer() throws IOException {ServerSocket serverSocket = new ServerSocket(SERVER_PORT, MAX_CONNECTION_LENGTH, InetAddress.getByName('localhost')); log('======準(zhǔn)備接收請求=====');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('發(fā)生錯(cuò)誤啦!');e.printStackTrace(); }} } private void writeHeaders(OutputStream outputStream) throws IOException {//必須包含返回頭,否則瀏覽器不識(shí)別outputStream.write('HTTP/1.1 200 OKrn'.getBytes());//一個(gè)rn代表換行添加新的頭,2次rn代表頭結(jié)束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();//此時(shí)的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文件下放入靜態(tài)資源啦,比如放一個(gè)index.html
然后啟動(dòng),打開瀏覽器輸入http://localhost:8888/index.html就能看到結(jié)果了!
以上就是Java 實(shí)現(xiàn)簡單靜態(tài)資源Web服務(wù)器的示例的詳細(xì)內(nèi)容,更多關(guān)于java 實(shí)現(xiàn)web服務(wù)器的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. XML入門精解之結(jié)構(gòu)與語法2. HTML DOM setInterval和clearInterval方法案例詳解3. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera4. 輕松學(xué)習(xí)XML教程5. Xml簡介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理6. HTML <!DOCTYPE> 標(biāo)簽7. CSS 使用Sprites技術(shù)實(shí)現(xiàn)圓角效果8. XML入門的常見問題(二)9. WMLScript的語法基礎(chǔ)10. 詳解CSS偽元素的妙用單標(biāo)簽之美
