首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

C/S 架構下 Java 應用程序運行流程詳解

     編輯:Java 相關知識

客戶端/服務器通信模型

C/S 架構採用基於連接的網絡通信模式:首先定義通信協議,創建 Socket 建立可靠連接,然後在連接上傳輸數據。典型的「請求-應答」流程如下:

  1. 服務器監聽端口
  2. 客戶機發出請求
  3. 服務器接收請求
  4. 服務器處理並返回結果
  5. 重複直至會話結束

Java 實現關鍵點

1. 服務器使用 ServerSocket

ServerSocket 處理客戶機連接請求。當客戶機連接時,分配新的 Socket 對象處理該客戶機通信,主線程繼續監聽新連接。

2. 服務器採用多線程機制

  • Server 對象本身是線程,run() 方法無限循環監聽連接
  • 新連接到來時,創建 Socket 實例與 Connection 線程對象
  • Connection 初始化通信流並處理所有與該客戶機的通信

3. 客戶機通信流程

  • 創建 Socket 連接服務器
  • 創建 DataInputStream 讀取數據、PrintStream 寫入數據
  • 從標準輸入讀取用戶數據發送給服務器,接收應答並輸出

完整代碼示例

服務端 Server.java

// Server.java
import java.io.*;
import java.net.*;

public class Server extends Thread {
    public final static int Default_Port = 6543;
    protected int port;
    protected ServerSocket listen_socket;

    public static void fail(Exception e, String msg) {
        System.err.println(msg + ": " + e);
        System.exit(1);
    }

    public Server(int port) {
        if (port == 0) port = Default_Port;
        this.port = port;
        try {
            listen_socket = new ServerSocket(port);
        } catch (IOException e) {
            fail(e, "Exception creating server socket");
        }
        System.out.println("Server: listening on port " + port);
        this.start();
    }

    public void run() {
        try {
            while (true) {
                Socket client_socket = listen_socket.accept();
                Connection c = new Connection(client_socket);
            }
        } catch (IOException e) {
            fail(e, "Exception while listening for connections");
        }
    }

    public static void main(String args[]) {
        int port = 0;
        if (args.length == 1) {
            try { port = Integer.parseInt(args[0]); }
            catch (NumberFormatException e) { port = 0; }
        }
        new Server(port);
    }
}

class Connection extends Thread {
    protected Socket client;
    protected DataInputStream in;
    protected PrintStream out;

    public Connection(Socket client_socket) {
        client = client_socket;
        try {
            in = new DataInputStream(client.getInputStream());
            out = new PrintStream(client.getOutputStream());
        } catch (IOException e) {
            try { client.close(); } catch (IOException e2) {}
            System.err.println("Exception while getting socket stream: " + e);
            return;
        }
        this.start();
    }

    public void run() {
        String line;
        StringBuffer revline;
        int len;
        try {
            for (;;) {
                line = in.readLine();
                if (line == null) break;
                len = line.length();
                revline = new StringBuffer(len);
                for (int i = len - 1; i >= 0; i--)
                    revline.append(line.charAt(i));
                out.println(revline);
            }
        } catch (IOException e) {}
        finally {
            try { client.close(); } catch (IOException e2) {}
        }
    }
}

客戶端 Client.java

// Client.java
import java.io.*;
import java.net.*;

public class Client {
    public static final int Default_Port = 6543;

    public static final void usage() {
        System.out.println("Usage: java Client [host] [port]");
        System.exit(0);
    }

    public static void main(String args[]) {
        int port = Default_Port;
        Socket s = null;
        if ((args.length != 1) && (args.length != 2)) usage();
        if (args.length == 2) {
            try { port = Integer.parseInt(args[1]); }
            catch (NumberFormatException e) { usage(); }
        }
        try {
            s = new Socket(args[0], port);
            DataInputStream sin = new DataInputStream(s.getInputStream());
            PrintStream sout = new PrintStream(s.getOutputStream());
            DataInputStream in = new DataInputStream(System.in);
            System.out.println("Connected to " + s.getInetAddress() + ":" + s.getPort());
            String line;
            for (;;) {
                System.out.print(" >");
                System.out.flush();
                line = in.readLine();
                if (line == null) break;
                sout.println(line);
                line = sin.readLine();
                if (line == null) {
                    System.out.println("Connection closed by server.");
                    break;
                }
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println(e);
        } finally {
            try { if (s != null) s.close(); } catch (IOException e2) {}
        }
    }
}

核心類說明

  • Socket:客戶端通信端點
  • ServerSocket:服務端監聽端口,接受連接並產生新 Socket
  • DataInputStream / PrintStream:處理文本數據的讀寫
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved