logo

Calculadora senzilla amb TCP a Java

Requisit previ: Programació de socket en Java La xarxa no conclou amb una comunicació unidireccional entre el client i el servidor. Per exemple, considereu un servidor que indica l'hora que escolta les peticions dels clients i respon amb l'hora actual al client. Les aplicacions en temps real solen seguir un model de sol·licitud-resposta per a la comunicació. El client normalment envia l'objecte de sol·licitud al servidor que després de processar la sol·licitud envia la resposta al client. En termes senzills, el client demana un recurs particular disponible al servidor i el servidor respon al recurs si pot verificar la sol·licitud. Per exemple, quan es prem Intro després d'introduir l'url desitjat, s'envia una sol·licitud al servidor corresponent que després respon enviant la resposta en forma d'una pàgina web que els navegadors són capaços de mostrar. En aquest article s'implementa una senzilla aplicació de calculadora on el client enviarà sol·licituds al servidor en forma d'equacions aritmètiques simples i el servidor respondrà amb la resposta a l'equació.

Programació del costat del client

Els passos a seguir pel costat del client són els següents:
  1. Obriu la connexió del sòcol
  2. Comunicació:En la part de comunicació hi ha un lleuger canvi. La diferència amb l'article anterior rau en l'ús tant dels fluxos d'entrada com de sortida per enviar equacions i rebre els resultats cap al servidor i des del servidor respectivament. DataInputStream i DataOutputStream s'utilitzen en lloc d'InputStream i OutputStream bàsics per fer-lo independent de la màquina. S'utilitzen els constructors següents:
      Public DataInputStream (InputStream in)
        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.
    Després de crear els fluxos d'entrada i sortida, utilitzem els mètodes readUTF i writeUTF dels fluxos creats per rebre i enviar el missatge respectivament.
      Public final String readUTF() llança 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() llança 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. Tancant la connexió.

Implementació del costat del client

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);  }  } } 
Sortida
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 

Programació del costat del servidor



Els passos implicats al costat del servidor són els següents:
  1. Establiu una connexió de presa.
  2. Processa les equacions procedents del client:Al costat del servidor també obrim tant inputStream com outputStream. Després de rebre l'equació, la processem i retornem el resultat al client escrivint al outputStream del sòcol.
  3. Tanqueu la connexió.

Implementació del costat del servidor

ordenar per aleatori en sql
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));  }  } } 
Sortida:
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. Article relacionat: Calculadora senzilla amb UDP a Java Crea un qüestionari