简要描述
一、目标 - 实现HTTP服务
- 不用框架利用Socket编程实现一个HTTP服务框架
- 实现基本的Request/Response封装
- 思考IO和线程模型之间的关系
二、网络插槽Socket
三、线程模型
四、NIO+Socket编程
五、简单的Http服务
1、RawHttpServer源码
/**
* @description: RawHttpServer
* @author: flygo
* @time: 2022/4/27 22:20
*/
public class RawHttpServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8001);
// Main thread
while (true) {
// Blocking...
// Thread ---> Sleep ---> Other Threads
var socket = serverSocket.accept();
System.out.println("A socket created");
var iptStream = new DataInputStream(socket.getInputStream());
var bfReader = new BufferedReader(new InputStreamReader(iptStream));
var requestBuilder = new StringBuilder();
String line = "";
// ReadLine -> line end "\n"
while (!(line = bfReader.readLine()).isBlank()) {
requestBuilder.append(line + "\n");
}
var request = requestBuilder.toString();
System.out.println(request);
var bfWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bfWriter.write("HTTP/1.1 200 ok\n\nHello Word\n");
bfWriter.flush();;
bfWriter.close();
}
}
}
2、通过curl 访问该HttpServer
$ curl http://localhost:8001
关注与赞助
飞鸽FlyGo官网
微信公众号
赞助
码字和开源离不开您的支持,感谢您的赞助和支持。
评论区