手写HTTP服务器

/**
 * 服务器核心类
 * @throws IOException 
 */
private ServerSocket serverSocket;
private int PORTNUMBER=9001;//端口号
private String FNRL = "\r\n";
private String SPACE = "  ";
public static void main(String[] args) throws IOException {
Server server = new Server();
server.start();
}
/**
 * 开启服务器监听
 * @throws IOException
 */
public void start() throws IOException{
//创建服务器端
 serverSocket = new ServerSocket(PORTNUMBER);
 System.out.println("服务器启动啦......");
 acceptClient();
 close();
}
/**
 * 接收客户端数据
 * @throws IOException
 */
public void acceptClient() throws IOException{
System.out.println("开始接收客户端数据......");
Socket socketClient = serverSocket.accept();
InputStream input = socketClient.getInputStream();
StringBuffer stringBuffer = new StringBuffer();
String msg = "";
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
//读取数据
while((msg=bufferedReader.readLine()).length()>0){
stringBuffer.append(msg+"\r\n");
if(msg==null){
break;
}
}
 responseDate(socketClient.getOutputStream());
System.out.println("接收的数据内容是"+stringBuffer.toString());
}
/**
 * 响应客户端
 * @param outputStream
 * @throws IOException
 */
public void responseDate(OutputStream outputStream) throws IOException{
//封装显示网页信息
StringBuffer responseDate = new StringBuffer();
responseDate.append("<html><head><title> this title </title></head> <body>welcome wangchi</body></html>");
//显示Http响应头
StringBuffer response = new StringBuffer();
response.append("HTTP/1.1").append(SPACE).append("200").append(SPACE).append("ok").append(FNRL);
response.append("Date:").append(new Date()).append(FNRL);
response.append("Content-Type: text/html;charset=UTF-8").append(FNRL);
response.append("Content-Length").append(responseDate.toString().getBytes().length).append(FNRL);
response.append(FNRL);
response.append(responseDate.toString());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
bw.write(response.toString());
bw.flush();
}
/**
 * 关闭资源
 */
public void close() throws IOException{
serverSocket.close();
}

猜你喜欢

转载自blog.csdn.net/wjc2013481273/article/details/80813651