【后端】BS(Browser Server)的小练习

BS(Browser Server)的小练习

需求:用户在浏览器输入网址(服务器中HTML文件地址),服务器给用户返回HTML网页。
主要练习IO流,服务端JAVA代码:

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

public class ceshi {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);//一定要寫在循環外面,否則端口會出問題
        while (true) {
            //創建服務器對象

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {


                        //創建客戶端瀏覽器對象
                        Socket socket = serverSocket.accept();
                        //得到客戶端對象的輸入流
                        InputStream inputStream = socket.getInputStream();
//        int len;
//        byte[] bytes=new byte[1024];
//        while((len=inputStream.read(bytes))!=-1){
//            System.out.println(new String(bytes));
//        }
                        //將字節輸入流轉為字符型緩衝流
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        //讀取一行
                        String line = bufferedReader.readLine();
                        System.out.println(line);
                        //對讀取的信息進行切割
                        String[] s = line.split(" ");
                        System.out.println(s[1]);
                        //去掉路徑前面的/
                        String substring = s[1].substring(1);
                        System.out.println(substring);
                        File file = new File(substring);
                        System.out.println(file.getAbsolutePath());
                        System.out.println(System.getProperty("user.dir"));
                        //創建本地文件輸入流讀取文件
                        FileInputStream fileInputStream = new FileInputStream(substring);
                        //使用socket對象得到輸出流
                        OutputStream outputStream = socket.getOutputStream();
                        //寫入協議
                        outputStream.write("HTTP/1.1 200 OK\r\n".getBytes());
                        outputStream.write("Content-Type:text/html\r\n".getBytes());
                        outputStream.write("\r\n".getBytes());
                        //一讀一寫複製文件
                        int len = 0;
                        byte[] bytes = new byte[1024];
                        while ((len = fileInputStream.read(bytes)) != -1) {
                            outputStream.write(bytes, 0, len);
                        }

                        socket.close();
                        fileInputStream.close();

                    } catch (IOException e) {
                        System.out.println(e);
                    }
                }
            }).start();


        }


    }
}

你可能感兴趣的:(后端)