流程
- 基于tcp协议封装
- 监听某个端口,当请求过来的时候
- 根据请求读取某个 **.html文件并返回
流程图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7f8e353abb769c46c4b9dd5a406a642a.png)
核心代码
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpTcpServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(80);
System.out.println("http服务器已经启动……");
while (true) {
Socket accept = serverSocket.accept();
new Thread(() -> {
OutputStream outputStream = null;
FileInputStream fileInputStream = null;
try {
outputStream = accept.getOutputStream();
File file = new File("E:\\custom_http\\index.html");
fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = fileInputStream.read(bytes);
outputStream.write(bytes, 0, len);
} catch (Exception e) {
} finally {
try {
if(fileInputStream != null) fileInputStream.close();
if (outputStream != null) outputStream.close();
if (accept != null) accept.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
}
效果展示
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b08e1370829f998708466eca0d4d2c71.png)
优化
- 增加了 根据地址访问不同的页面
- 增加了找不到页面报500错误给前端
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpTcpServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(80);
System.out.println("http服务器已经启动……");
while (true) {
Socket accept = serverSocket.accept();
new Thread(() -> {
OutputStream outputStream = null;
FileInputStream fileInputStream = null;
InputStream inputStream = null;
try {
outputStream = accept.getOutputStream();
inputStream = accept.getInputStream();
byte[] acceptByte = new byte[1024];
int reqLen = inputStream.read(acceptByte);
String reqText = new String(acceptByte, 0, reqLen);
System.out.println(reqText);
String address = reqText.split("\n\r")[0].split(" ")[1];
File file = new File("E:\\custom_http" + address);
fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = fileInputStream.read(bytes);
outputStream.write(bytes, 0, len);
} catch (Exception e) {
e.printStackTrace();
try {
outputStream.write("500".getBytes());
} catch (IOException ex) {
ex.printStackTrace();
}
} finally {
try {
if(fileInputStream != null) fileInputStream.close();
if (outputStream != null) outputStream.close();
if (accept != null) accept.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
}