122、(案例)模拟BS案例

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/*
服务器端:实现可以通过浏览器访问
注意:
1、要把web文件夹拷贝到工程和src同一个级别
2、访问网址输入http://127.0.0.1:8080/Day15/web/index.html
3、浏览器解析服务器会写的html页面,如果页面中有图片,那么浏览器就会单独开启一个线程,读取服务器的图片,
每一张图片,就请求一次。所以我们就要让服务器一直处于监听状态,客户端请求一次,服务器就会写一次
 */
public class BSServer {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(8080);

        while(true){
            try{
                Socket accept = ss.accept();
                InputStream inputStream = accept.getInputStream();

                /*int len = 0;
                byte[] bytes = new byte[1024];
                while((len = inputStream.read(bytes)) != -1){
                    System.out.println(new String(bytes,0,len));
                }*/
                //把网络字节输入流对象,转换为字符缓冲输入流
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
                /*把客户端请求信息的第一行读出来,里面包含了请求数据的位置信息,例如:
                 GET /Day15/web/index.html HTTP/1.1 但是该信息里面有一些不必要的信息,我们要进行切割
                 */
                String line = br.readLine();

                //把读取的信息的中间部分取出来,以空格为切割:/Day15/web/index.html
                String[] s = line.split(" ");

                //把路径前面的/去掉,进行截取获得:Day15/web/index.html
                String substring = s[1].substring(1);
                //打印每次请求路径
                System.out.println(substring);

                //一获取的字符串为路径去本地文件获取数据
                FileInputStream fis = new FileInputStream(substring);

                //使用socket中的方法getOutputStream获取网络字节输出outputStream对象
                OutputStream os = accept.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);
                }

                //释放资源
                os.close();
                fis.close();
                accept.close();
            }catch (IOException E){
                E.printStackTrace();
            }
        }

        //ss.close();
    }
}

 


版权声明:本文为l0510402015原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。