📜  在Java中使用 TCP 的简单计算器

📅  最后修改于: 2022-05-13 01:55:16.504000             🧑  作者: Mango

在Java中使用 TCP 的简单计算器

先决条件: Java中的套接字编程
网络只是不以客户端和服务器之间的单向通信结束。例如,考虑一个时间告诉服务器,它侦听客户端的请求并以当前时间响应客户端。实时应用程序通常遵循请求-响应模型进行通信。

客户端通常将请求对象发送到服务器,服务器在处理请求后将响应发送回客户端。简单来说,客户端请求服务器上可用的特定资源,如果服务器可以验证请求,则服务器响应它的资源。例如,当输入所需的url后按下回车键时,会向相应的服务器发送请求,然后服务器以浏览器能够显示的网页形式发送响应来进行响应。
在本文中,实现了一个简单的计算器应用程序,其中客户端将以简单算术方程的形式向服务器发送请求,服务器将响应方程的答案。

客户端编程

客户端涉及的步骤如下 -

  1. 打开套接字连接
  2. 通讯:在通讯部分,有细微的变化。与上一篇文章的不同之处在于使用输入和输出流分别向服务器发送方程和从服务器接收结果。使用 DataInputStream 和 DataOutputStream 代替基本的 InputStream 和 OutputStream 以使其独立于机器。使用以下构造函数 -
    • 公共数据输入流(输入流输入)
      Syntax: public DataInputStream(InputStream in)
      Parameters:
      in - The underlying InputStream.
      Creates a DataInputStream that uses the specified underlying InputStream.
    • 公共数据输出流(输入流输入)
      Syntax: public DataOutputStream(OutputStream out)
      Parameters:
      out - The underlying OutputStream.
      Creates a DataOutputStream that uses the specified underlying OutputStream.

    创建输入输出流后,我们使用创建的流方法的 readUTF 和 writeUTF 分别接收和发送消息。

    • 公共最终字符串 readUTF()
      抛出 IOException
      Reads the string encoded using UTF8 encoding.
      Throws:
      IOException -  the stream has been closed and the contained input stream 
      does not support reading after close,
      or another I/O error occurs
      
    • 公共最终字符串 writeUTF()
      抛出 IOException
      Writes the string encoded using UTF8 encoding.
      Throws:
      IOException -  the stream has been closed and the contained input stream 
      does not support reading after close,
      or another I/O error occurs
      
  3. 关闭连接。

客户端实现

// Java program to illustrate Client Side Programming
// for Simple Calculator using TCP
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
  
public class Calc_Client
{
    public static void main(String[] args) throws IOException
    {
        InetAddress ip = InetAddress.getLocalHost();
        int port = 4444;
        Scanner sc = new Scanner(System.in);
  
        // Step 1: Open the socket connection.
        Socket s = new Socket(ip, port);
  
        // Step 2: Communication-get the input and output stream
        DataInputStream dis = new DataInputStream(s.getInputStream());
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
  
        while (true)
        {
            // Enter the equation in the form-
            // "operand1 operation operand2"
            System.out.print("Enter the equation in the form: ");
            System.out.println("'operand operator operand'");
  
            String inp = sc.nextLine();
  
            if (inp.equals("bye"))
                break;
  
            // send the equation to server
            dos.writeUTF(inp);
  
            // wait till request is processed and sent back to client
            String ans = dis.readUTF();
            System.out.println("Answer=" + ans);
        }
    }
}

输出

Enter the equation in the form: 'operand operator operand'
5 * 6
Answer=30
Enter the equation in the form: 'operand operator operand'
5 + 6
Answer=11
Enter the equation in the form: 'operand operator operand'
9 / 3
Answer=3

服务器端编程

服务器端涉及的步骤如下 -

  1. 建立套接字连接。
  2. 处理来自客户端的方程:在服务器端,我们同时打开 inputStream 和 outputStream。收到等式后,我们对其进行处理并将结果通过写入套接字的输出流返回给客户端。
  3. 关闭连接。

服务器端实现

// Java program to illustrate Server Side Programming
// for Simple Calculator using TCP
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
  
public class Calc_Server
{
    public static void main(String args[]) throws IOException
    {
  
        // Step 1: Establish the socket connection.
        ServerSocket ss = new ServerSocket(4444);
        Socket s = ss.accept();
  
        // Step 2: Processing the request.
        DataInputStream dis = new DataInputStream(s.getInputStream());
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
  
        while (true)
        {
            // wait for input
            String input = dis.readUTF();
  
            if(input.equals("bye"))
                break;
  
            System.out.println("Equation received:-" + input);
            int result;
  
            // Use StringTokenizer to break the equation into operand and
            // operation
            StringTokenizer st = new StringTokenizer(input);
  
            int oprnd1 = Integer.parseInt(st.nextToken());
            String operation = st.nextToken();
            int oprnd2 = Integer.parseInt(st.nextToken());
  
            // perform the required operation.
            if (operation.equals("+"))
            {
                result = oprnd1 + oprnd2;
            }
  
            else if (operation.equals("-"))
            {
                result = oprnd1 - oprnd2;
            }
            else if (operation.equals("*"))
            {
                result = oprnd1 * oprnd2;
            }
            else
            {
                result = oprnd1 / oprnd2;
            }
            System.out.println("Sending the result...");
  
            // send the result back to the client.
            dos.writeUTF(Integer.toString(result));
        }
    }
}

输出:

Equation received:-5 * 6
Sending the result...
Equation received:-5 + 6
Sending the result...
Equation received:-9 / 3
Sending the result...

注意:为了在系统上测试上述程序,请确保您先运行服务器程序,然后再运行客户端程序。确保您在客户端控制台中,并从那里以“operand1 运算符 ”格式输入等式,然后按 Enter。请求公式的答案将仅显示在客户端控制台中。最后要终止通信,输入“bye”(不带引号)并回车。

相关文章:
在Java中使用 UDP 的简单计算器