- SocketServer
public class TomcatServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8080);
while (true) {
Socket socket = serverSocket.accept();
new Thread(() -> {
try {
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
while (true) {
//创建一个字节集合
List<Byte> contentBytes = new ArrayList<Byte>();
//先读取第一行
while (true) {
int byteData = is.read();
contentBytes.add((byte) byteData);
// System.out.println("byteToStringStr" + byteToStringStr(contentBytes));
if (byteData == 10 && (countBytes(contentBytes, (byte) 10) == 1)) {
//读取到了换行符
System.out.println("Http请求行:" + byteToString(contentBytes));
}
//继续判断是否是以 \r\n\r\n 结束,表示请求头结束了
if (endWithHeader(contentBytes)){
System.out.println("完整的Http协议请求: \n" + byteToString(contentBytes));
break;
}
}
writeSse(os);
//os.write(("已经到请求,共计字节数:" + contentBytes.size() + "\r\n").getBytes(StandardCharsets.UTF_8) );
//os.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
public static Integer countBytes(List<Byte> byteList,byte target) {
Map<Byte, Integer> countMap = new HashMap<>();
for (Byte b : byteList) {
if (countMap.containsKey(b)) {
countMap.put(b, countMap