How to create HTTP Server in Java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
/** * Java program to create a simple HTTP Server to demonstrate how to use * ServerSocket and Socket class. * *
@author Javin Paul*/
public class SimpleHTTPServer
{
public static void main(String args[]) throws IOException
{
ServerSocket server = new ServerSocket(8080);
System.out.println("Listening for connection on port 8080 ....");
while (true)
{
try (Socket socket = server.accept())
{
//读取request
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
BufferedReader reader = new BufferedReader(isr);
String line = reader.readLine();
while (!line.isEmpty())
{
System.out.println(line);
line = reader.readLine();
}
//写入response
Date today = new Date();
String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + today;
socket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
}
}
}
}
建立web server,监听8080端口上的connection
ServerSocket server = new ServerSocket(8080);
读取connection。这是一个阻塞函数。当有从client过来的connect时,这个函数会返回一个socket,用来读取request和写入response。server会一直循环监听connect,直至server自己stop。
Socket socket = server.accept()
读取request
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
写入response
socket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
这种写法,没有处理多个connect。当一个connect正在处理的时候,其他的connect必须等待。使用thread或Java NIO non blocking selectors and channels来处理并发。