logo

Calculadora simple usando TCP en Java

Requisito previo: Programación de sockets en Java La creación de redes simplemente no concluye con una comunicación unidireccional entre el cliente y el servidor. Por ejemplo, considere un servidor que indica la hora que escucha la solicitud de los clientes y responde con la hora actual al cliente. Las aplicaciones en tiempo real suelen seguir un modelo de solicitud-respuesta para la comunicación. El cliente generalmente envía el objeto de solicitud al servidor que, después de procesar la solicitud, envía la respuesta al cliente. En términos simples, el cliente solicita un recurso particular disponible en el servidor y el servidor responde con ese recurso si puede verificar la solicitud. Por ejemplo, cuando se presiona Enter después de ingresar la URL deseada, se envía una solicitud al servidor correspondiente que luego responde enviando la respuesta en forma de una página web que los navegadores son capaces de mostrar. En este artículo se implementa una aplicación de calculadora simple en la que el cliente enviará solicitudes al servidor en forma de ecuaciones aritméticas simples y el servidor responderá con la respuesta a la ecuación.

Programación del lado del cliente

Los pasos involucrados en el lado del cliente son los siguientes:
  1. Abra la conexión del enchufe
  2. Comunicación:En la parte de comunicación hay un ligero cambio. La diferencia con el artículo anterior radica en el uso de los flujos de entrada y salida para enviar ecuaciones y recibir los resultados hacia y desde el servidor respectivamente. Flujo de entrada de datos y Flujo de salida de datos se utilizan en lugar de InputStream y OutputStream básicos para hacerlo independiente de la máquina. Se utilizan los siguientes constructores:
      DataInputStream público (InputStream en)
        Syntax:   public DataInputStream(InputStream in)   Parameters:   in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream.
      flujo de salida de datos público (flujo de entrada en)
        Syntax:   public DataOutputStream(OutputStream out)   Parameters:   out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream.
    Después de crear los flujos de entrada y salida, utilizamos los métodos readUTF y writeUTF de los flujos creados para recibir y enviar el mensaje respectivamente.
      La cadena final pública readUTF() lanza 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 
      La cadena final pública writeUTF() lanza 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. Cerrando la conexión.

Implementación del lado del cliente

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);  }  } } 
Producción
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ón del lado del servidor



Los pasos involucrados en el lado del servidor son los siguientes:
  1. Establezca una conexión de enchufe.
  2. Procese las ecuaciones provenientes del cliente:En el lado del servidor también abrimos tanto inputStream como OutputStream. Después de recibir la ecuación, la procesamos y devolvemos el resultado al cliente escribiendo en el flujo de salida del socket.
  3. Cierra la conexión.

Implementación del lado del servidor

cambiar nombre directorio linux
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));  }  } } 
Producción:
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. Artículo relacionado: Calculadora simple usando UDP en Java Crear cuestionario