完整客戶端程式碼
import java.io.*;
import java.net.*;
public class SimpleWebClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 80);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
DataInputStream in = new DataInputStream(socket.getInputStream())) {
out.writeBytes("GET / HTTP/1.0\r\n\r\n");
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (UnknownHostException e) {
System.err.println("主機解析失敗: " + e.getMessage());
} catch (IOException e) {
System.err.println("I/O 錯誤: " + e.getMessage());
}
}
}
關鍵改進點
- try-with-resources:Java 7+ 自動關閉資源,避免洩漏
- 異常分類處理:區分 DNS 解析失敗與 I/O 錯誤
- 正確的 HTTP 請求格式:以
\r\n\r\n 結束請求頭
常見埠號對照表
| 服務 | 埠號 |
| echo | 7 |
| daytime | 13 |
| FTP | 21 |
| telnet | 23 |
| SMTP | 25 |
| finger | 79 |
| HTTP | 80 |
| POP3 | 110 |
| HTTPS | 443 |
最佳實務總結
- 指定正確主機與埠號建立 Socket
- 使用緩衝資料流提升效能
- 遵循應用層協定格式(如 HTTP)
- 妥善處理異常與資源釋放
- 設定連線與讀取逾時避免無限阻塞