logo

Calculadora Simples usando TCP em Java

Pré-requisito: Programação de soquete em Java A rede simplesmente não termina com uma comunicação unidirecional entre o cliente e o servidor. Por exemplo, considere um servidor informando a hora que escuta as solicitações dos clientes e responde com a hora atual ao cliente. Os aplicativos em tempo real geralmente seguem um modelo de solicitação-resposta para comunicação. O cliente geralmente envia o objeto de solicitação ao servidor que após processar a solicitação envia a resposta de volta ao cliente. Em termos simples, o cliente solicita um determinado recurso disponível no servidor e o servidor responde ao recurso se puder verificar a solicitação. Por exemplo, quando enter é pressionado após inserir o URL desejado, uma solicitação é enviada ao servidor correspondente, que então responde enviando a resposta na forma de uma página da web que os navegadores são capazes de exibir. Neste artigo, é implementado um aplicativo de calculadora simples, onde o cliente enviará solicitações ao servidor na forma de equações aritméticas simples e o servidor responderá com a resposta à equação.

Programação do lado do cliente

As etapas envolvidas no lado do cliente são as seguintes:
  1. Abra a conexão do soquete
  2. Comunicação:Na parte de comunicação há uma ligeira alteração. A diferença com o artigo anterior está na utilização dos fluxos de entrada e saída para enviar equações e receber os resultados de e para o servidor, respectivamente. DataInputStream e DataOutputStream são usados ​​em vez de InputStream e OutputStream básicos para torná-lo independente da máquina. Os seguintes construtores são usados ​​-
      DataInputStream público (InputStream em)
        Syntax:   public DataInputStream(InputStream in)   Parameters:   in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream.
      DataOutputStream público (InputStream em)
        Syntax:   public DataOutputStream(OutputStream out)   Parameters:   out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream.
    Após criar os streams de entrada e saída utilizamos os métodos readUTF e writeUTF dos streams criados para receber e enviar a mensagem respectivamente.
      public final String readUTF() lanç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() lanç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. Fechando a conexão.

Implementação do lado do 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);  }  } } 
Saída
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 

Programação do lado do servidor



As etapas envolvidas no lado do servidor são as seguintes:
  1. Estabeleça uma conexão de soquete.
  2. Processe as equações vindas do cliente:No lado do servidor também abrimos inputStream e outputStream. Depois de receber a equação, nós a processamos e retornamos o resultado ao cliente escrevendo no outputStream do soquete.
  3. Feche a conexão.

Implementação no lado do servidor

como ler um arquivo csv em 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));  }  } } 
Saída:
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. Artigo relacionado: Calculadora Simples usando UDP em Java Criar questionário