logo

Простий калькулятор із використанням TCP у Java

Необхідна умова: Програмування сокетів на Java Мережа просто не завершується одностороннім зв’язком між клієнтом і сервером. Наприклад, розглянемо сервер визначення часу, який слухає запити клієнтів і відповідає клієнту поточним часом. Програми реального часу зазвичай використовують модель запит-відповідь для спілкування. Клієнт зазвичай надсилає об’єкт запиту на сервер, який після обробки запиту надсилає відповідь назад клієнту. Простіше кажучи, клієнт запитує певний ресурс, доступний на сервері, і сервер відповідає цьому ресурсу, якщо він може перевірити запит. Наприклад, коли після введення потрібної URL-адреси натискається клавіша enter, запит надсилається на відповідний сервер, який потім відповідає, надсилаючи відповідь у формі веб-сторінки, яку можуть відображати браузери. У цій статті реалізовано простий додаток-калькулятор, у якому клієнт надсилатиме запити серверу у формі простих арифметичних рівнянь, а сервер відповідатиме відповіддю на рівняння.

Програмування на стороні клієнта

На стороні клієнта виконуються такі дії:
  1. Відкрийте з'єднання сокета
  2. Зв'язок:У комунікаційній частині є невеликі зміни. Різниця з попередньою статтею полягає у використанні як вхідного, так і вихідного потоків для надсилання рівнянь і отримання результатів на сервер і з нього відповідно. DataInputStream і DataOutputStream використовуються замість базових InputStream і OutputStream, щоб зробити його незалежним від машини. Використовуються наступні конструктори -
      публічний DataInputStream(InputStream в)
        Syntax:   public DataInputStream(InputStream in)   Parameters:   in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream.
      public DataOutputStream(InputStream in)
        Syntax:   public DataOutputStream(OutputStream out)   Parameters:   out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream.
    Після створення вхідного та вихідного потоків ми використовуємо readUTF та writeUTF створених потоків, щоб отримати та надіслати повідомлення відповідно.
      public final String 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 
      public final String 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
// 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
Java
// 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... 
Note: In order to test the above programs on the system please make sure that you run the server program first and then the client one. Make sure you are in the client console and from there enter the equation in the format-'operand1 operator operand2' and press Enter. Answer to the requested equation will be shown in the client console only. Finally to terminate the communication type 'bye' (without quotes) and hit enter. Пов'язана стаття: Простий калькулятор з використанням UDP у Java Створіть вікторину