Java笔记-使用ServerSocket构建HTTP服务器
生活随笔
收集整理的這篇文章主要介紹了
Java笔记-使用ServerSocket构建HTTP服务器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
運行截圖如下;
瀏覽器訪問:
后端打印:
項目結構如下:
HttpCallback.java
package cn.it1995.http;public interface HttpCallback {byte[] onResponse(String request); }?HttpServer.java
package cn.it1995.http;import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;public class HttpServer {private boolean mRunning;private HttpCallback mCallback;public HttpServer(HttpCallback Callback) {this.mCallback = Callback;}public void startHttpServer(){if(mRunning){return;}mRunning = true;try {ServerSocket serverSocket = new ServerSocket(80);while (mRunning){Socket accept = serverSocket.accept();ExecutorService threadPool = Executors.newCachedThreadPool();threadPool.execute(new HttpThread(accept, mCallback));}}catch (IOException e) {e.printStackTrace();}} }?HttpThread.java
package cn.it1995.http;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket;public class HttpThread implements Runnable{private Socket mSocket;private HttpCallback mCallback;public HttpThread(Socket socket, HttpCallback httpCallback){mSocket = socket;mCallback = httpCallback;}@Overridepublic void run() {try {BufferedReader reader = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));String content;StringBuffer request = new StringBuffer();while((content = reader.readLine()) != null&& !content.trim().isEmpty()){request.append(content).append("\n");}System.out.println("request:\n" + request);byte[] response = new byte[0];if(mCallback != null){response = mCallback.onResponse(request.toString());}String responseFirstLine = "HTTP/1.1 200 OK \r\n";String responseHead = "Content-type:" + "text/html" + "\r\n";OutputStream outputStream = mSocket.getOutputStream();outputStream.write(responseFirstLine.getBytes());outputStream.write(responseHead.getBytes());outputStream.write("\r\n".getBytes());outputStream.write(response);mSocket.close();}catch (IOException e) {e.printStackTrace();}} }?Main.java
package cn.it1995;import cn.it1995.http.HttpCallback; import cn.it1995.http.HttpServer;public class Main {public static void main(String[] args) {System.out.println("start http server");HttpServer server = new HttpServer(new HttpCallback() {@Overridepublic byte[] onResponse(String request) {return "Hello World".getBytes();}});server.startHttpServer();} }?
源碼打包下載地址:
https://github.com/fengfanchen/Java/tree/master/Server
總結
以上是生活随笔為你收集整理的Java笔记-使用ServerSocket构建HTTP服务器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt笔记-递归获取文件夹中文件(含过滤文
- 下一篇: NginxJava笔记-Webservi