模拟BS服务器分析与模拟BS服务器代码实现
模拟BS服务器分析
模拟BS服务器代码实现
package DemoThreadPool01; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class TCP { public static void main(String[] args) throws IOException { //创建服务器ServerSocket对象 ServerSocket server = new ServerSocket(8080); while (true){ //使用accept获取Socket Socket sc = server.accept(); new Thread(new Runnable() { @Override public void run() { try { //获取InputStream网络字节输入流 InputStream is = sc.getInputStream(); if (is != null) { //创建缓冲流 , 转换为字符缓冲输入流 BufferedReader bw = new BufferedReader(new InputStreamReader(is)); //GET /IOTest/web/index.html HTTP/1.1 String line; line = bw.readLine(); //分割路劲 String[] path = line.split(" "); //获取路径 IOTest/web/index.html String filename = path[1].substring(1); //filename = IOTest/web/index.html System.out.println("filename:" + filename); //创建本地字节输入流 FileInputStream FileInputStream fis = new FileInputStream(filename); OutputStream os = sc.getOutputStream(); //写入Http响应 os.write("HTTP/1.1 200 OK\r\n".getBytes()); os.write("Content-Type:text/html\r\n".getBytes()); //必须要写入空行,否则浏览器不解析 os.write("\r\n".getBytes()); //一读一写浏览器 int len = 0; byte[] bytes = new byte[1024]; while ((len = fis.read(bytes)) != -1) { //写入服务器 os.write(bytes, 0, len); } fis.close(); sc.close(); } } catch (IOException e) { e.printStackTrace(); } } }).start(); } } }