logo

Prosty kalkulator wykorzystujący protokół TCP w Javie

Warunek wstępny: Programowanie gniazd w Javie Praca w sieci nie kończy się na jednokierunkowej komunikacji pomiędzy klientem a serwerem. Rozważmy na przykład serwer pomiaru czasu, który nasłuchuje żądań klientów i odpowiada klientowi, podając aktualny czas. Aplikacje czasu rzeczywistego zazwyczaj korzystają z modelu komunikacji typu żądanie-odpowiedź. Klient zazwyczaj wysyła obiekt żądania do serwera, który po przetworzeniu żądania odsyła odpowiedź z powrotem do klienta. Mówiąc najprościej, klient żąda określonego zasobu dostępnego na serwerze, a serwer odpowiada temu zasóbowi, jeśli może zweryfikować żądanie. Na przykład, gdy po wprowadzeniu żądanego adresu URL zostanie naciśnięty klawisz Enter, żądanie zostanie wysłane do odpowiedniego serwera, który następnie odpowie, wysyłając odpowiedź w postaci strony internetowej, którą przeglądarki mogą wyświetlić. W tym artykule zaimplementowano prostą aplikację kalkulatora, w której klient będzie wysyłał żądania do serwera w postaci prostych równań arytmetycznych, a serwer odpowie odpowiedzią na równanie.

Programowanie po stronie klienta

Kroki po stronie klienta są następujące:
  1. Otwórz połączenie gniazdowe
  2. Komunikacja:W części komunikacyjnej następuje niewielka zmiana. Różnica w stosunku do poprzedniego artykułu polega na wykorzystaniu zarówno strumieni wejściowych, jak i wyjściowych do wysyłania równań i odbierania wyników odpowiednio do i z serwera. Strumień wejściowy danych I Strumień wyjściowy danych są używane zamiast podstawowego strumienia wejściowego i wyjściowego, aby zapewnić jego niezależność od komputera. Używane są następujące konstruktory -
      publiczny DataInputStream(InputStream in)
        Syntax:   public DataInputStream(InputStream in)   Parameters:   in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream.
      publiczny DataOutputStream (InputStream in)
        Syntax:   public DataOutputStream(OutputStream out)   Parameters:   out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream.
    Po utworzeniu strumieni wejściowych i wyjściowych używamy metod readUTF i writeUTF utworzonych strumieni, aby odpowiednio odebrać i wysłać wiadomość.
      publiczny końcowy ciąg readUTF() zgłasza wyjątek 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 
      publiczny końcowy ciąg writeUTF() zgłasza wyjątek 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. Zamknięcie połączenia.

Implementacja po stronie 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);  }  } } 
Wyjście
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 

Programowanie po stronie serwera



Kroki po stronie serwera są następujące:
  1. Nawiąż połączenie gniazdowe.
  2. Przetwórz równania pochodzące od klienta:Po stronie serwera otwieramy również strumień wejściowy i strumień wyjściowy. Po otrzymaniu równania przetwarzamy je i zwracamy wynik klientowi zapisując go w strumieniu wyjściowym gniazda.
  3. Zamknij połączenie.

Implementacja po stronie serwera

samouczek dotyczący mikrousług
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));  }  } } 
Wyjście:
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. Powiązany artykuł: Prosty kalkulator wykorzystujący UDP w Javie Utwórz quiz