这是模仿B/S模式,浏览器向服务器发送请求,服务器进行响应
浏览器解析服务器回写的html页面,页面中如果有图片,那么浏览器就会单独的开启一个线程,读取服务器的图片;我们就的让服务器一直处于监听状态, 客户端请求一次, 服务器就回写一次
public class TcpBSService {
public static void main(String[] args) throws IOException {
//1.创建一个服务器ServerSocket对象,,和系统要指定的端口号
ServerSocket serverSocket = new ServerSocket(8888);
//2.使用accept方法获取到请求的客户端对象(浏览器)
while(true){
Socket socket = serverSocket.accept();
//浏览器解析服务器回写的html页面,页面中如果有图片,那么浏览器就会单独的开启一个线程,读取服务器的图片
//我们就的让服务器一直处于监听状态, 客户端请求一次, 服务器就回写一次
new Thread(new Runnable() {
@Override
public void run() {
try {
//使用Socket对象中的方法get InputStream,获取到网络字节输入流Inputstream对象
InputStream inputStream = socket.getInputStream();
把inputStream网络字节输入流对象,转换为字符缓冲输入流
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//把客户端请求信息的第一行读取出来GET /11 Net/web/index. html HTTP/1.1
String line = bufferedReader.readLine();
//把读取的信息进行切割,只要中间部分/11_ Net/web/index. html
String[] array = line.split(" ");
String urlPath = "C:\\Users\\maoxiaohao\\IdeaProjects\\";
String htmlPath = array[1].substring(1);
//创建一个本地字节输入流,构造方法中绑定要读取的html路径
FileInputStream fileInputStream = new FileInputStream(urlPath+htmlPath);
//使用Socket中的方法getOutputStream获取网络字节输出流OutputStream对象
OutputStream os = socket.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());
//一读一写复制文件,把服务读取的html文件回写到客户端
byte[] bytes = new byte[1024];
int len;
while ((len= fileInputStream.read(bytes)) != -1){
os.write(bytes,0,len);
//system.out.println(new String(bytes,0,len));
}
inputStream.close();
socket.close();
}catch (IOException e){
System.out.println(e);
}
}
}).start();
}
}
}