本文主要是介绍手写服务器httpserver_准备_http协议_http工具JAVA197-198,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
来源:http://www.bjsxt.com/
一、S02E197_01手写服务器httpserver_准备_http协议
package com.test.server;import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
/*** 创建服务器,并启动* 1、请求* 2、响应*/
public class ServerForResponse {private ServerSocket server;private static final String CRLF = "\r\n";private static final String BLANK = " ";public static void main(String[] args) {ServerForResponse server = new ServerForResponse();server.start();}/*** 启动方法*/public void start(){ try {server = new ServerSocket(8888);this.receive();} catch (IOException e) {e.printStackTrace();}}/*** 接收客户端*/private void receive(){try {Socket client =server.accept();StringBuilder sb =new StringBuilder();byte[] date = new byte[20480];int len = client.getInputStream().read(date);//接收客户端的请求信息String requestInfo = new String(date,0,len).trim(); System.out.println(requestInfo);//响应StringBuilder responseContext = new StringBuilder();responseContext.append("<html><head><title>HTTP响应示例</title>" + "</head><body>Hello World!</body></html>");StringBuilder response = new StringBuilder();//1)HTTP协议版本、状态代码、描述response.append("HTTP/1.1").append(BLANK).append("200").append(BLANK).append("OK").append(CRLF);//2)响应头(Response Head)response.append("Server:test Server/0.0.1").append(CRLF);response.append("Date:").append(new Date()).append(CRLF);response.append("Content-type:text/html;charset=GBK").append(CRLF);//正文长度:字节长度response.append("Content-Length:").append(responseContext.toString().getBytes().length).append(CRLF);//3)正文之前response.append(CRLF);//4)正文response.append(responseContext);//输出流BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));bw.write(response.toString());bw.flush();bw.close();} catch (IOException e) {//e.printStackTrace();}}/*** 停止服务器*/public void stop(){}
}
二、S02E198_01手写服务器httpserver_准备_http工具
HTTP响应分析
HTTP工具:HttpWatch——捕捉信息,便于查看请求响应内容
这篇关于手写服务器httpserver_准备_http协议_http工具JAVA197-198的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!