1 package BsServersocket;
2
3 import java.io.*;
4 import java.net.ServerSocket;
5 import java.net.Socket;
6
7 public class Client {
8 /**
9 * 模拟BS服务器:
10 * 创建BS版本的TCP服务器
11 *
12 * //1.创建服务器ServerSocket,和系统要指定的端口号
13 * //2.使用accept获取到请求的客户端对象(浏览器)
14 * //3.使用Socket对下个中的getInputStream,获取到网络字节输入流InputStream对象
15 * //4.使用网络字节输入流InputStream对象中的方法read获取客户端的请求信息
16 * http://127.0.0.1:8080/文件目录
17 * 服务器需要给客户端回写一个html页面(文件)
18 * 我们需要读取index_html文件,就必须知道这个文件的地址
19 * 这个文件的地址就是请求信息的第一行
20 * 可以使用BufferedReader中的方法readLine读取一行
21 * new BufferedReader(new InputStreamReader(is)把网络字节输入流转为字符缓冲输入流
22 * 使用String类的方法split根据空格切割字符串获取中间部分
23 * 使用String的方法subString(1)截取字符串获取到html文件路径
24 * 服务器创建本地字节输入流根据获取到的文件路径读取html文件
25 * 注意:
26 * 写出时先固定写:
27 * //写入HTTP协议响应,固定方法
28 * out.write("HTTP/1.1 200 ok、\r\n".getBytes());
29 * out.write("Content-Type:text/html\r\n".getBytes());
30 * //必须要写入空行,否则浏览器不解析
31 * out.write("\r\n".getBytes());
32 * 服务器端使用网络字节输出流把读取到的文件写到客户端
33 *不显示图片:
34 * 浏览器解析服务器回写的html页面,页面中如果有图片,那么浏览器就会单独在开启一个线程,读取服务器图片
35 * 让服务器一直处于监听状态(while)
36 * 使用线程
37 *
38 */
39
40 public static void main(String[] args) throws IOException {
41 //1.创建服务器ServerSocket,和系统要指定的端口号
42 ServerSocket serverSocket = new ServerSocket(8080);
43 //使用while循环让服务器一直跑
44 while (true) {
45 //2.使用accept获取到请求的客户端对象(浏览器)
46 Socket socket = serverSocket.accept();
47 //开启线程
48 new Thread(new Runnable() {
49 @Override
50 public void run() {
51 try{
52 //3.使用Socket对下个中的getInputStream,获取到网络字节输入流InputStream对象
53 InputStream is = socket.getInputStream();
54 //4.使用网络字节输入流InputStream对象中的方法read获取客户端的请求信息
55 /*byte[] bytes = new byte[1024];
56 int len = is.read(bytes);
57 String str = new String(bytes);*/
58 //使用BufferedReader把网络字节输入流转换为缓冲输入流读取第一行
59 BufferedReader br = new BufferedReader(new InputStreamReader(is));
60 String s = br.readLine();
61 //使用String类的split方法切割得到文件路径
62 String[] s1 = s.split(" ");
63 //使用String类的subString方法截取
64 String htmlpath = s1[1].substring(1);
65 //服务器创建本地字节输入流根据获取到的文件路径读取html文件
66 FileInputStream fis = new FileInputStream(htmlpath);
67 //务器端使用网络字节输出流把读取到的文件写到客户端
68 OutputStream ous = socket.getOutputStream();
69 //出时先固定写
70 //写入HTTP协议响应,固定方法
71 ous.write("HTTP/1.1 200 ok、\r\n".getBytes());
72 ous.write("Content-Type:text/html\r\n".getBytes());
73 //必须要写入空行,否则浏览器不解析
74 ous.write("\r\n".getBytes());
75 //一读一写回写
76 int len = 0;
77 byte[] bytes = new byte[1024];
78 while ((len = fis.read(bytes)) != -1) {
79 ous.write(bytes, 0, len);
80 }
81 fis.close();
82 socket.close();
83 }catch (IOException e){
84 e.printStackTrace();
85 }
86
87 }
88 }).start();
89
90 }
91
92 }
93 }