核心代码如下:
public class DiyTomcat1 {
public void run() throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("======服务启动成功========");
while (!serverSocket.isClosed()) {
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
System.out.println("执行客户请求:" + Thread.currentThread());
System.out.println("收到客户请求");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
String msg = null;
while ((msg = reader.readLine()) != null) {
if (msg.length() == 0) {
break;
}
System.out.println(msg);
}
String rspHeaderStr = "HTTP/1.1 200" + "\r\n" + "Content-Type:text/html" + "\r\n\r\n";
String resp = rspHeaderStr + "OK";
OutputStream outputStream = socket.getOutputStream();
System.out.println("=====rsp====");
System.out.println(resp);
outputStream.write(resp.getBytes());
outputStream.flush();
outputStream.close();
socket.close();
}
}
}
这是一个最基本的socket通信流程:
- 首先通过创建一个ServerSocket实例, 该实例拥有监听端口的能力
- 通过调用serverSocket的accept方法来监听并接受连接
- 当有客户端连接上来会返回一个socket对象,该对象代表着这次通信的连接
- 通过socket.getInputStream来获得客户端向服务端的输入(流)
- 通过socket.getOutputStream来获得服务端向客户端的输出流,并通过调用write方法将我们要发送的数据写入
- String rspHeaderStr = "HTTP/1.1 200" + "\r\n" + "Content-Type:text/html" + "\r\n\r\n"; 是为了构造出一个http 协议的头部,方便客户端解析(如果是浏览器http请求过来,可以方便浏览器直接展示处理)
代码地址:
https://github.com/ZhongJinHacker/diy-tomcat/tree/base-tomcat