回显主页和favorite、主页中有img图片标签
回显主页和favorite
代码案例:
/** * 解析封装为一个request对象 * @param s * @return */ private static Request parseRequest(String s){ Request req = new Request(); String[] split = s.split("\r\n"); String[] spl = split[0].split(" "); req.setMethod(spl[0]); req.setUri(spl[1]); return req; }
public static void main(String[] args) throws IOException { byte b = 0x3f; byte2Hex(b); ServerSocket server = new ServerSocket(8080); System.out.println("服务器已经启动,监听端口在8080..."); while (true){ Socket socket = server.accept(); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); byte[] buf = new byte[1024*1024]; new Thread(new Runnable() { @Override public void run() { int len = 0; try { len = is.read(buf); if (len == -1) return; System.out.println("读到的字节数量是:"+len); String hexMsg = byteArr2HexStr(buf, len); System.out.println(hexMsg); String s = new String(buf,0,len); System.out.println(s); Request request = parseRequest(s); // HTTP1.1协议 状态码200 正确 回车换行 String line1 = "HTTP/1.1 200 OK\r\n"; // 内容的类型是普通文本,回车换行 String line2 = "Content-Type:text/plain\r\n"; // 回车换行 final String line3 = "\r\n"; String file = null; if (request.getUri().equals("/") || request.getUri().equals("/index.html")){ line2 = "Content-Type:text/html\r\n"; file = "index.html"; } // 固定的响应三行 os.write(line1.getBytes()); os.write(line2.getBytes()); os.write(line3.getBytes()); // 如果file不为空,说明需要回文件给浏览器 if (file != null){ FileInputStream fis = new FileInputStream(file); while ((len=fis.read(buf)) !=-1){ os.write(buf,0,len); } }else { // 返回浏览器的文本内容 os.write((""+count).getBytes()); count++; } // 主动刷新一次 os.flush(); } catch (IOException e) { e.printStackTrace(); }finally { if (socket != null){ try { // 关闭资源 socket.close(); }catch (IOException e){ e.printStackTrace(); } } } } }).start(); } }
主页中有img图片标签
代码案例:
if (request.getUri().equals("/") || request.getUri().equals("/index.html")){ line2 = "Content-Type:text/html\r\n"; file = "index.html"; }else if (request.getUri().equals("favicon.ioc")){ line2 = "Content-Type:image/x-icon\r\n"; file = "favicon.ico"; }else if (request.getUri().endsWith(".jsp") || request.getUri().endsWith("jpeg")){ line2 = "Content-Type:image/jpeg\r\n"; // 过滤首字母/ file = request.getUri().substring(1); }