public class Server02 {
private ServerSocket serverSocket;
public static void main(String[] args) {
Server02 server = new Server02();
server.start();
}
//启动服务
public void start() {
try {
serverSocket = new ServerSocket(8888);
receive();
} catch (IOException e) {
e.printStackTrace();
System.out.println("服务器启动失败....");
}
}
//
public void receive() {
try {
Socket client = serverSocket.accept();
System.out.println("一个客户端建立了连接....");
InputStream is = client.getInputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
//bw.write("hahahaha");
byte[] datas = new byte[1024*1024];
int len = is.read(datas);
String requestInfo = new String(datas, 0, len);
System.out.println(requestInfo);
StringBuilder content = new StringBuilder();
content.append("<html>");
content.append("<head>");
content.append("<title>");
content.append("服务器响应成功");
content.append("</title>");
content.append("</head>");
content.append("<body>");
content.append("终于回来了。。。。");
content.append("</body>");
content.append("</html>");
int size = content.toString().getBytes().length;
StringBuilder responseInfo = new StringBuilder();
String blank = " ";
String CRLF = "\r\n";
//返回
//1、响应状态行: HTTP/1.1 200 OK
responseInfo.append("HTTP/1.1").append(blank);
responseInfo.append(200).append(blank);
responseInfo.append("OK").append(CRLF);
//2、响应头(最后一行空行):
responseInfo.append("Date:").append(new Date()).append(CRLF);
responseInfo.append("Server:").append("shsxt Server/0.01;charset=GBK").append(CRLF);
responseInfo.append("Content-type:test/html").append(CRLF);
responseInfo.append("Content-lenth:").append(size).append(CRLF).append(CRLF);
//3、正文
responseInfo.append(content.toString());
//4、写出到客户端
bw.write(responseInfo.toString());
bw.flush();
} catch (IOException e) {
e.printStackTrace();
System.out.println("客户端错误");
}
}
//停止服务
public void stop() {
}
}
使用浏览器的RESTer插件模拟GET和POST操作,却一直失败得不到返回的结果。