平時在使用tomcat、jetty時,只是使用裏面的servlet、filter等,歷來沒想過它們如何同瀏覽器進行交互的。工做中遇到一些問題,在同其它同事交流及學習源碼的過程當中,才明白底層原來走的也是socket,才知道所謂的NIO是什麼。。。html
瞭解NIO以前,確定得先了解BIO,出於學習的目的 ,使用BIO寫一個簡單的http服務器DEMO:瀏覽器輸入任何請求,後臺打印出請求信息並在瀏覽器中輸出Hello Worldjava
1 import java.io.BufferedReader; 2 import java.io.BufferedWriter; 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.InputStreamReader; 6 import java.io.OutputStream; 7 import java.io.OutputStreamWriter; 8 import java.net.InetSocketAddress; 9 import java.net.ServerSocket; 10 import java.net.Socket; 11 12 public class BioServer { 13 private ServerSocket serverSocket; 14 15 private String ip; 16 17 private int port; 18 19 public BioServer(String ip, int port) { 20 this.ip = ip; 21 this.port = port; 22 } 23 24 public void startListen() throws IOException { 25 serverSocket = new ServerSocket(); 26 serverSocket.bind(new InetSocketAddress(ip, port)); //建立對指定端口及IP的監聽 27 28 while (true) { 29 accept(); 30 } 31 } 32 33 private void accept() throws IOException { 34 //收到客戶端的請求 35 Socket socket = serverSocket.accept(); 36 37 //輸入流用於接收客戶端傳輸過來的數據 38 InputStream in = socket.getInputStream(); 39 InputStreamReader reader = new InputStreamReader(in); 40 BufferedReader br = new BufferedReader(reader); 41 String line = null; 42 while ((line = br.readLine()) != null) { 43 System.out.println(line); 44 //按照HTTP協議,請求頭和請求體之間爲一空行分隔 45 if ("".equals(line)) { 46 break; 47 } 48 } 49 50 //輸出流用於向客戶端發送響應消息,需聽從HTTP協議格式 51 OutputStream out = socket.getOutputStream(); 52 OutputStreamWriter writer = new OutputStreamWriter(out); 53 BufferedWriter bw = new BufferedWriter(writer); 54 bw.write("HTTP/1.1 200 OK\n"); 55 bw.write("Content-Type: text/html; charset=UTF-8\n"); 56 bw.write("\n"); 57 bw.write("<html>"); 58 bw.write("<head>"); 59 bw.write("<title>"); 60 bw.write("BIO Http Server"); 61 bw.write("</title>"); 62 bw.write("</head>"); 63 bw.write("<body>"); 64 bw.write("<h1>Hello World!</h1>"); 65 bw.write("</body>"); 66 bw.write("</html>"); 67 68 //必須在請求讀取和響應寫入都處理完畢以後才能夠調用close方法,將輸入流關閉也會致使輸出流不可用 69 bw.close(); 70 writer.close(); 71 out.close(); 72 br.close(); 73 reader.close(); 74 in.close(); 75 socket.close(); 76 } 77 78 public static void main(String[] args) { 79 BioServer server = new BioServer("127.0.0.1", 8080); 80 try { 81 server.startListen(); 82 } catch (IOException e) { 83 e.printStackTrace(); 84 } 85 } 86 }