java 实现简单的http服务器
1、废话不多说,代码如下
package com.linhuaming.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* http服务器 测试
*/
public class HttpServerTest {
public static void main(String[] args) throws IOException {
// ServerSocket指定端口port
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("启动服务---port:8080");
while(true){
// 阻塞到有连接访问,拿到socket
Socket socket = serverSocket.accept();
System.out.println("get socket from:"+socket.hashCode());
// STEP. 启动线程
new Thread(()->{
try {
// STEP. 获取输入流、输出流
OutputStream outputStream = null;
InputStream inputStream = null;
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
// STEP. 获取输入内容
byte[] bytes = new byte[inputStream.available()];
int result = inputStream.read(bytes);
if (result != -1) {
System.out.println(new String(bytes));
}
// STEP. 响应内容
// http 状态
String httpStatus = "200 OK";
// String httpStatus = "404 Not Found";
// String httpStatus = "500 Internal Server Error";
// 状态行、响应头部、空行、响应信息
String body = "<h1>hello</h1>";
String responseStatusLine = "HTTP/1.1 "+httpStatus+"\r\n";
String responseHeader = "";
responseHeader += "Content-Length: " + body.getBytes().length + "\r\n";
responseHeader += "Content-Type: text/html; charset-utf-8\r\n";
String responseLine = "\r\n";
String responseBody = body + "\r\n";
String response = responseStatusLine + responseHeader +responseLine + responseBody;
// 输出响应内容、关闭流
outputStream.write(response.getBytes());//按照协议,将返回请求由outputStream写入
outputStream.flush();
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
}catch (Exception e){
e.printStackTrace();
}
},String.valueOf(socket.hashCode())).start();
}
}
}
2、打开postman、chrome浏览器都可以,访问http://127.0.0.1:8080/test 即可,如下图所示
postman 访问
chrome 访问
linhuaming