名詞定義:
以下例子以 java 的連接傾向插座 [connection-oriented (TCP) socket],要用 Socket 類別製作。
DateServer.java
/**
* Time-of-day server listening to port 6013.
*
* Figure 3.21
*
* @author Silberschatz, Gagne, and Galvin.
* Operating System Concepts - Ninth Edition
* Copyright John Wiley & Sons - 2013.
*/
import java.net.*;
import java.io.*;
public class DateServer
{
public static void main(String[] args) {
try {
/* 創建一個 ServerSocket 對象,並在端口 6013 上監聽進入的連接請求 */
ServerSocket sock = new ServerSocket(6013);
// now listen for connections
while (true) {
/* 這行代碼調用 accept() 方法,這會阻塞並等待客戶端連接。一旦有客戶端連接,將返回一個 Socket 對象,表示與該客戶端的連接 */
Socket client = sock.accept();
// we have a connection
/* 這行代碼獲取與客戶端連接的輸出流,並創建一個 PrintWriter 對象,這樣可以方便地向客戶端發送文本數據。第二個參數 true 使得自動刷新輸出流 */
PrintWriter pout = new PrintWriter(client.getOutputStream(), true);
// write the Date to the socket
/* 媽,我在這裡!創建一個 Date 對象(表示當前日期和時間),並將其轉換為字符串後發送給客戶端 */
pout.println("Mary here!" + new java.util.Date().toString());
// close the socket and resume listening for more connections
client.close();
}
}
catch (IOException ioe) {
System.err.println(ioe);
}
}
}
DateClient.java
/**
* Client program requesting current date from server.
*
* Figure 3.22
*
* @author Silberschatz, Gagne and Galvin
* Operating System Concepts - Eighth Edition
*/
import java.net.*;
import java.io.*;
public class DateClient
{
public static void main(String[] args) {
try {
// this could be changed to an IP name or address other than the localhost
Socket sock = new Socket("127.0.0.1",6013);
InputStream in = sock.getInputStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
String line;
while( (line = bin.readLine()) != null)
System.out.println(line);
sock.close();
}
catch (IOException ioe) {
System.err.println(ioe);
}
}
}
Terminal
安裝 java
sudo apt update
sudo apt install openjdk-17-jdk
確認 java 安裝成功並編譯 .java 檔案,生成相應的 .class 文件
java -version
javac DateServer.java DateClient.java
分別在一個 Terminal 執行 Server
java DateServer
在另一個 Terminal 執行 Client
java DateClient
結果
參考: