1. 程式人生 > 實用技巧 >建立BS版本TCP伺服器

建立BS版本TCP伺服器

package com.chunzhi.Test04BSTCP;

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

/*
   建立BS版本TCP伺服器
 */
public class TCPServer {
    public static void main(String[] args) throws IOException {
        // 1.建立一個伺服器ServerSocket,和系統要指定的埠號
        ServerSocket server = new ServerSocket(8888);

        
while (true) { new Thread(new Runnable() { @Override public void run() { try { // 2.使用accept方法獲取到請求的客戶端物件(瀏覽器) Socket socket = server.accept(); // 3.使用Socket物件中的方法getInputStream,獲取網路位元組輸入流InputStream物件
InputStream is = socket.getInputStream(); // 4.使用InputStream中的方法read讀取客戶端請求的資訊 /*int len = 0; byte[] bytes = new byte[1024]; while ((len = is.read(bytes)) != -1) { System.out.println(new String(bytes, 0, len)); }
*/ // 5.把is網路位元組輸入流物件,轉換為字元緩衝輸入流 BufferedReader br = new BufferedReader(new InputStreamReader(is)); // 6.把客戶端請求資訊的第一行讀出來 String line = br.readLine(); // GET /Day11_Net/web/index.html HTTP/1.1 // 6-1.把讀取的第一行資訊進行切割,只要中間部分 String[] arr = line.split(" "); // /Day11_Net/web/index.html // 6-2. 把路徑前面的/去掉,進行擷取 String htmlPath = arr[1].substring(1); // Day11_Net/web/index.html // 7.建立一個本地的位元組輸入流,構造法中繫結要讀取的html路徑 FileInputStream fis = new FileInputStream(htmlPath); // 8.使用socket中的方法getOutputStream獲取網路輸出流物件。位元組輸出流,將檔案寫給客戶端 OutputStream os = socket.getOutputStream(); // 9.寫入HTTP協議響應頭,固定寫法 os.write("HTTP/1.1 200 OK\r\n".getBytes()); os.write("Content-Type:text/html\r\n".getBytes()); // 9-1.必須要寫入空行,否則瀏覽器不解析 os.write("\r\n".getBytes()); // 10.一讀一些複製檔案,把伺服器讀取的HTML檔案回寫到客戶端 int len = 0; byte[] bytes = new byte[1024]; while ((len = fis.read(bytes)) != -1) { os.write(bytes, 0, len); } // 11.釋放資源 os.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }).start(); } // 伺服器不需要關閉 // server.close(); } }