logo

Calculatrice simple utilisant TCP en Java

Condition préalable: Programmation de sockets en Java La mise en réseau ne se limite pas à une communication unidirectionnelle entre le client et le serveur. Par exemple, considérons un serveur d'indication de l'heure qui écoute les demandes des clients et répond avec l'heure actuelle au client. Les applications en temps réel suivent généralement un modèle demande-réponse pour la communication. Le client envoie généralement l'objet de requête au serveur qui, après avoir traité la requête, renvoie la réponse au client. En termes simples, le client demande une ressource particulière disponible sur le serveur et le serveur y répond s'il peut vérifier la demande. Par exemple, lorsque vous appuyez sur Entrée après avoir entré l'URL souhaitée, une requête est envoyée au serveur correspondant qui répond ensuite en envoyant la réponse sous la forme d'une page Web que les navigateurs sont capables d'afficher. Dans cet article, une application de calculatrice simple est implémentée dans laquelle le client enverra des requêtes au serveur sous la forme d'équations arithmétiques simples et le serveur répondra avec la réponse à l'équation.

Programmation côté client

Les étapes à suivre côté client sont les suivantes :
  1. Ouvrir la connexion socket
  2. Communication:Dans la partie communication, il y a un léger changement. La différence avec l'article précédent réside dans l'utilisation des flux d'entrée et de sortie pour envoyer des équations et recevoir les résultats vers et depuis le serveur respectivement. Flux d'entrée de données et DataOutputStream sont utilisés à la place des InputStream et OutputStream de base pour le rendre indépendant de la machine. Les constructeurs suivants sont utilisés -
      public DataInputStream (InputStream dans)
        Syntax:   public DataInputStream(InputStream in)   Parameters:   in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream.
      public DataOutputStream (InputStream dans)
        Syntax:   public DataOutputStream(OutputStream out)   Parameters:   out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream.
    Après avoir créé les flux d'entrée et de sortie, nous utilisons les méthodes readUTF et writeUTF des flux créés pour recevoir et envoyer le message respectivement.
      public final String readUTF() lève 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() lance 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. Fermeture de la connexion.

Implémentation côté 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);  }  } } 
Sortir
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 

Programmation côté serveur



Les étapes impliquées côté serveur sont les suivantes :
  1. Établissez une connexion socket.
  2. Traitez les équations provenant du client :Côté serveur, nous ouvrons également à la fois inputStream et outputStream. Après avoir reçu l'équation, nous la traitons et renvoyons le résultat au client en écrivant sur le flux de sortie du socket.
  3. Fermez la connexion.

Implémentation côté serveur

tranche de tableau 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));  }  } } 
Sortir:
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 connexe : Calculatrice simple utilisant UDP en Java Créer un quiz