logo

Jednoduchá kalkulačka využívajúca TCP v jazyku Java

Predpoklad: Programovanie soketov v jazyku Java Sieť sa nekončí jednosmernou komunikáciou medzi klientom a serverom. Zvážte napríklad časový server, ktorý počúva požiadavky klientov a odpovedá klientovi aktuálnym časom. Aplikácie v reálnom čase sa pri komunikácii zvyčajne riadia modelom žiadosť-odpoveď. Klient zvyčajne odošle objekt požiadavky na server, ktorý po spracovaní požiadavky odošle odpoveď späť klientovi. Zjednodušene povedané, klient požiada o konkrétny zdroj dostupný na serveri a server naň odpovie, ak môže požiadavku overiť. Napríklad, keď sa po zadaní požadovanej adresy URL stlačí enter, odošle sa požiadavka na príslušný server, ktorý potom odpovie odoslaním odpovede vo forme webovej stránky, ktorú prehliadače dokážu zobraziť. V tomto článku je implementovaná jednoduchá aplikácia kalkulačky, v ktorej klient odošle požiadavky na server vo forme jednoduchých aritmetických rovníc a server odpovie odpoveďou na rovnicu.

Programovanie na strane klienta

Kroky na strane klienta sú nasledovné:
  1. Otvorte pripojenie zásuvky
  2. komunikácia:V komunikačnej časti je mierna zmena. Rozdiel oproti predchádzajúcemu článku spočíva v použití vstupného aj výstupného toku na odosielanie rovníc a prijímanie výsledkov na server a zo servera. DataInputStream a DataOutputStream sa používajú namiesto základných InputStream a OutputStream, aby boli strojovo nezávislé. Používajú sa nasledujúce konštruktory -
      verejný DataInputStream (InputStream in)
        Syntax:   public DataInputStream(InputStream in)   Parameters:   in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream.
      verejný DataOutputStream (InputStream in)
        Syntax:   public DataOutputStream(OutputStream out)   Parameters:   out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream.
    Po vytvorení vstupného a výstupného toku použijeme metódy readUTF a writeUTF vytvorených tokov na prijatie a odoslanie správy.
      public final String readUTF() vyvolá 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() vyvolá 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. Uzavretie spojenia.

Implementácia na strane klienta

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);  }  } } 
Výstup
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 

Programovanie na strane servera



Kroky na strane servera sú nasledovné -
  1. Vytvorte zásuvkové pripojenie.
  2. Spracujte rovnice prichádzajúce od klienta:Na strane servera tiež otvárame inputStream aj outputStream. Po prijatí rovnice ju spracujeme a výsledok vrátime späť klientovi zápisom na výstupný prúd zásuvky.
  3. Zatvorte spojenie.

Implementácia na strane servera

ako vrátiť pole v jave
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));  }  } } 
výstup:
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. Súvisiaci článok: Jednoduchá kalkulačka využívajúca UDP v jazyku Java Vytvoriť kvíz