TCP 客戶端使用 Socket 類別主動發起連線,需指定主機名稱與埠號:
Socket clientSocket = new Socket("example.com", 80);
常見知名埠號:HTTP(80)、HTTPS(443)、FTP(21)、SSH(23)、SMTP(25)、POP3(110)。
連線成功後,透過 getInputStream()、getOutputStream() 取得資料流,建議包裝為 DataInputStream/DataOutputStream 或 BufferedReader/PrintWriter 便於文字處理:
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
// 發送 HTTP GET 請求
out.writeBytes("GET / HTTP/1.0\r\n\r\n");
// 讀取回應
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
out.close()in.close()clientSocket.close()務必在 finally 區塊關閉資源,避免洩漏。Java 7+ 可使用 try-with-resources 自動管理。