package com.io;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class BrowServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(2222);
while(true){
try{
Socket client = server.accept();
InputStream in = client.getInputStream();
byte[] buf = new byte[1024];
in.read(buf);
//in.close();
System.out.println("request from client " + client.getInetAddress().getHostAddress());
System.out.println(new String(buf));
OutputStream out = client.getOutputStream();
DataOutputStream outStream = new DataOutputStream(client.getOutputStream());
//outStream.write("Hello".getBytes());
//outStream.flush();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outStream,"UTF-8"));
bufferedWriter.write(response());
bufferedWriter.flush();
client.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
public static String response() throws Exception{
// 请求头部
StringBuilder responseInfo = new StringBuilder();
final String CRLF = "\r\n";
final String BLANK = " ";
responseInfo.append("HTTP/1.1").append(BLANK);
responseInfo.append("200 OK").append(CRLF);
responseInfo.append("Date:").append(new Date()).append(CRLF);
responseInfo.append("Server:").append("shsxt?Server/0.0.1;charset=UTF-8").append(CRLF);
responseInfo.append("Content-type:text/html").append(CRLF);
// 请求体
StringBuilder responseInfoBody = new StringBuilder();
responseInfoBody.append("<html>");
responseInfoBody.append("<head>");
responseInfoBody.append("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">");
responseInfoBody.append("</head>");
responseInfoBody.append("</html>");
responseInfoBody.append("登录页面");
int len = responseInfoBody.toString().getBytes("utf-8").length;
responseInfo.append("Content-length:").append(len).append(CRLF);
responseInfo.append(CRLF);
responseInfo.append(responseInfoBody.toString());
return responseInfo.toString();
}
}