使用 Java 實現 TCP 簡單計算器


網際網路協議套件包含各種協議,這些協議使裝置能夠透過網際網路進行通訊。TCP 是此套件中最常見的協議。它是一種面向連線的協議,這意味著它在兩個裝置之間維持已建立的連線,直到通訊結束。這就是在網路衝浪、傳送電子郵件和傳輸檔案時使用它的原因。

在本文中,我們將使用 Java 中的 TCP 開發一個簡單的客戶端-伺服器端計算器。客戶端將請求操作,伺服器將在計算後將結果傳送到客戶端裝置。

Java 網路

讓我們首先簡要了解一些關於 Java 網路的基本概念。

InetAddress

IP 地址是一個 32 位或 128 位無符號數字,用於唯一標識網際網路上的裝置。記住 IP 主機的名稱比記住數字地址更容易。因此,我們需要使用“InetAddress”類將其封裝起來。我們使用其內建方法“getLcalHost()”來檢索 LocalHost 的 IP 地址。

Socket

它是 Java 網路概念的基礎,它允許裝置同時為多個客戶端提供服務。有兩種 TCP 套接字類。一個是“ServerSocket”類,用於接收並向客戶端裝置傳送結果的伺服器;另一個是“Socket”類,用於客戶端請求資訊。

I/O 流

流是在 Java 網路中執行輸入和輸出操作時使用的抽象。透過使用“getInputStream()”“getOutputStream()”,我們可以訪問與“Socket”類關聯的輸入和輸出流。

使用 TCP 的計算器程式

客戶端程式

程式碼工作原理

  • 我們首先匯入兩個最重要的包,名為“java.net”以訪問所有關於 Java 網路的類,以及“java.io”用於輸入和輸出流。“java.util”包用於使用“Scanner”類。

  • 獲取 LocalHost 地址,然後將埠號和地址儲存在“Socket”類的物件中。

  • 定義兩個名為“inpStrm”的物件來接收資料,以及“outpStrm”的物件以流的形式傳送資料。

  • 現在,在 try 塊內部,我們將要求使用者輸入以請求操作並相應地接收結果。

示例

import java.io.*;
import java.net.*;
import java.util.*;
public class ClientCal {
   public static void main(String[] args) throws IOException {
      // fetching address of localhost
      InetAddress addr = InetAddress.getLocalHost();
      Scanner inp = new Scanner(System.in);
      // establishing socket connection
      Socket sock = new Socket(addr, 6666);
      // to send and receive data through streams
      DataInputStream inpStrm = new DataInputStream(sock.getInputStream());
      DataOutputStream outpStrm = new DataOutputStream(sock.getOutputStream());
      try {
         while (true) {
            System.out.println("Type 1 for Addition");
		   System.out.println("Type 2 for Subtraction");
		   System.out.println("Type 3 for Multiplication");
		   System.out.println("Type 4 for Division");
            System.out.println("Enter your choice: ");
            int oprtr = inp.nextInt();
            // Type 0 for cut the connection
            if (oprtr == 0) {
               break;
            }
            // sending the operator for operation
            outpStrm.writeInt(oprtr); 
            // reading result from server
            String res = inpStrm.readUTF();
            System.out.println("Your Result for the given operation = " + res);
         }
      }
      // to handle exception
      catch(Exception exp) {
         System.out.println(exp);
      } 
   }
}

伺服器端程式

程式碼工作原理

  • 首先,與客戶端建立連線。

  • 然後從客戶端讀取請求。

  • 在 try 塊內部,使用 switch case 執行操作並將結果傳送到客戶端裝置。

  • catch 塊用於處理執行時期間的任何型別的異常。

示例

import java.io.*;
import java.net.*;
import java.util.*; 
public class ServeCalc {
   public static void main(String args[]) throws IOException {
      // establishing the socket connection
      ServerSocket Serve = new ServerSocket(6666);
      Socket sock = Serve.accept();
      // to send and receive data through streams
      DataInputStream inpStrm = new DataInputStream(sock.getInputStream());
      DataOutputStream outpStrm = new DataOutputStream(sock.getOutputStream());
      try {
         while (true) {
            // reading input from client
            int oprtr = inpStrm.readInt();
            System.out.println("Client has requested for " + oprtr + " operation");
            int res = 0;
            int data1 = 15;
            int data2 = 5;
            switch(oprtr) {
	            case 1 : 
	               res = data1 + data2;
                  outpStrm.writeUTF(Integer.toString(res));
		            break;
	            case 2 :
		            res = data1 - data2;
                  outpStrm.writeUTF(Integer.toString(res));
		            break;
	            case 3 :
		            res = data1 * data2;
                  outpStrm.writeUTF(Integer.toString(res));
		            break;
	            case 4 :
		            res = data1 / data2;
                  outpStrm.writeUTF(Integer.toString(res));
		            break;
	            default :
		         outpStrm.writeUTF(" You have given invalid choice! ");
		            break; 
            }
            System.out.println("Result sent to the client...");
         }
      }
      // to handle exception
      catch(Exception exp) {
         System.out.println(exp);
      } 
   }
}

要執行這兩個程式,請在本地計算機上同時開啟兩個 cmd。在第一個 cmd 介面上,編譯並執行伺服器端程式,然後在另一個介面上執行客戶端程式。

伺服器端輸出

D:\Java Programs>javac ServeCalc.java
D:\Java Programs>java ServeCalc
Client has requested for 1 operation
Result sent to the client...
Client has requested for 2 operation
Result sent to the client...
Client has requested for 3 operation
Result sent to the client...
Client has requested for 4 operation
Result sent to the client...
java.net.SocketException: Connection reset

客戶端輸出

D:\Java Programs>javac ClientCal.java 
D:\Java Programs>java ClientCal
Type 1 for Addition
Type 2 for Subtraction
Type 3 for Multiplication
Type 4 for Division
Enter your choice:
1
Your Result for the given operation = 20
Type 1 for Addition
Type 2 for Subtraction
Type 3 for Multiplication
Type 4 for Division
Enter your choice:
2
Your Result for the given operation = 10
Enter your choice:
0

當我們輸入 0 時,連線將被終止,程式將停止執行。

結論

在本文中,我們學習了 Java 網路的一些基本概念。還討論了使用傳輸控制協議的簡單計算器的伺服器端和客戶端程式。我們瞭解瞭如何在 Java 中在客戶端和伺服器裝置之間建立連線。

更新於: 2023年5月15日

767 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告