ServerSocket 的 accept() 預設回傳 Socket 實例。若需回傳擴充功能的子類別(如內建 HTTP 請求頭解析),可覆寫 accept() 並呼叫 implAccept(Socket) 注入未連線的子類別實例。本文示範建立 HttpSocket 並整合至 HttpServerSocket,自動解析瀏覽器發送的 HTTP 請求頭。
class HttpSocket extends Socket {
public String getRequestHeaders() throws Exception {
InputStreamReader isr = new InputStreamReader(getInputStream());
BufferedReader br = new BufferedReader(isr);
String s = "", result = "";
while (!(s = br.readLine()).equals(""))
result += s + "\r\n";
return result;
}
}
class HttpServerSocket extends ServerSocket {
public HttpServerSocket(int port) throws IOException { super(port); }
public Socket accept() throws IOException {
Socket s = new HttpSocket();
implAccept(s); // 注入子類別實例
return s;
}
}
public class CustomAccept {
public static void main(String[] args) throws Exception {
HttpServerSocket server = new HttpServerSocket(1234);
HttpSocket socket = (HttpSocket) server.accept();
System.out.println(socket.getRequestHeaders()); // 輸出 HTTP 請求頭
server.close();
}
}
java server.CustomAccepthttps://localhost:1234implAccept 為 protected final,必須在子類別中呼叫。Socket 需強制轉型為子類別才能呼叫新增方法。自訂 accept() 回傳類型是 ServerSocket 少為人知但強大的擴充點,能在連接建立瞬間賦予 Socket 額外能力,簡化上層協議處理邏輯。