流程
- 基于tcp协议封装
- 监听某个端口,当请求过来的时候
- 根据请求读取某个 **.html文件并返回
流程图
核心代码
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();
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
效果展示
优化
- 增加了 根据地址访问不同的页面
- 增加了找不到页面报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();
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51