Socket 代表 TCP 連線。常用建構子:
Socket(InetAddress addr, int port)Socket(String host, int port)建立成功後,本地端會綁定任意可用埠口。失敗拋出 IOException 或 UnknownHostException。
getInputStream():讀取伺服器資料getOutputStream():傳送資料給伺服器建議套裝 BufferedReader 與 PrintWriter 處理文字行。
Socket socket = new Socket("localhost", 10000);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("DATE");
System.out.println(in.readLine()); // 伺服器回應
out.println("PAUSE");
out.println("DOW");
System.out.println(in.readLine());
out.println("DOM");
System.out.println(in.readLine());
out.println("DOY");
System.out.println(in.readLine());
in.close(); out.close(); socket.close();
| 方法 | 說明 |
|---|---|
| getLocalAddress() | 本地 IP 位址 |
| getLocalPort() | 本地埠口 |
| getInetAddress() | 遠端 IP 位址 |
| getPort() | 遠端埠口 |
java SSClient # 連線 localhost
java SSClient www.example.com # 連線指定主機