模擬B\S服務器
public static void main(String[] args) throws IOException {
//創(chuàng)建一個服務器ServerSocket,和系統(tǒng)要指定的端口號
ServerSocket server = new ServerSocket(8080);
瀏覽器解析服務器回寫的html頁面,頁面中如果有圖片,那么瀏覽器就會單獨的開啟一個線程,讀取服務器的圖片
我們就的讓服務器一直處于監(jiān)聽狀態(tài),客戶端請求一次,服務器就回寫一次
while(true){
//使用accept方法獲取到請求的客戶端對象(瀏覽器)
Socket socket = server.accept();
new Thread(new Runnable() {
@Override
public void run() {
try {
//使用Socket對象中的方法getInputStream,獲取到網(wǎng)絡字節(jié)輸入流InputStream對象
InputStream is = socket.getInputStream();
//把is網(wǎng)絡字節(jié)輸入流對象,轉(zhuǎn)換為字符緩沖輸入流
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//把客戶端請求信息的第一行讀取出來 GET /11_Net/web/index.html HTTP/1.1
String line = br.readLine();
System.out.println(line);
//把讀取的信息進行切割,只要中間部分 /11_Net/web/index.html
String[] arr = line.split(" ");
//把路徑前邊的/去掉,進行截取 11_Net/web/index.html
String htmlpath = arr[1].substring(1);
//創(chuàng)建一個本地字節(jié)輸入流,構(gòu)造方法中綁定要讀取的html路徑
FileInputStream fis = new FileInputStream(htmlpath);
//使用Socket中的方法getOutputStream獲取網(wǎng)絡字節(jié)輸出流OutputStream對象
OutputStream os = socket.getOutputStream();
// 寫入HTTP協(xié)議響應頭,固定寫法
os.write("HTTP/1.1 200 OK\r\n".getBytes());
os.write("Content-Type:text/html\r\n".getBytes());
// 必須要寫入空行,否則瀏覽器不解析
os.write("\r\n".getBytes());
//使用網(wǎng)絡字節(jié)輸入流InputStream對象中的方法read讀取客戶端的請求信息
//一讀一寫復制文件,把服務讀取的html文件回寫到客戶端
int len = 0;
byte[] bytes = new byte[1024];
while((len = fis.read(bytes))!=-1){
os.write(bytes,0,len);
}
//釋放資源
fis.close();
}catch (IOException e){
e.printStackTrace();
}finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
//server.close();
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者