logo

Einfacher Rechner mit TCP in Java

Voraussetzung: Socket-Programmierung in Java Networking endet einfach nicht mit einer einseitigen Kommunikation zwischen Client und Server. Stellen Sie sich beispielsweise einen Zeitmeldeserver vor, der auf Anfragen der Clients lauscht und dem Client mit der aktuellen Uhrzeit antwortet. Echtzeitanwendungen folgen für die Kommunikation in der Regel einem Anfrage-Antwort-Modell. Der Client sendet normalerweise das Anforderungsobjekt an den Server, der nach der Verarbeitung der Anforderung die Antwort an den Client zurücksendet. Vereinfacht ausgedrückt fordert der Client eine bestimmte, auf dem Server verfügbare Ressource an und der Server antwortet dieser Ressource, wenn er die Anfrage überprüfen kann. Wenn beispielsweise nach Eingabe der gewünschten URL die Eingabetaste gedrückt wird, wird eine Anfrage an den entsprechenden Server gesendet, der dann antwortet, indem er die Antwort in Form einer Webseite sendet, die die Browser anzeigen können. In diesem Artikel wird eine einfache Rechneranwendung implementiert, bei der der Client Anfragen in Form einfacher arithmetischer Gleichungen an den Server sendet und der Server mit der Antwort auf die Gleichung antwortet.

Clientseitige Programmierung

Die auf der Clientseite erforderlichen Schritte sind wie folgt:
  1. Öffnen Sie die Socket-Verbindung
  2. Kommunikation:Im Kommunikationsteil gibt es eine leichte Änderung. Der Unterschied zum vorherigen Artikel liegt in der Verwendung sowohl des Eingabe- als auch des Ausgabestreams zum Senden von Gleichungen und zum Empfangen der Ergebnisse an bzw. vom Server. DataInputStream Und DataOutputStream werden anstelle des grundlegenden InputStream und OutputStream verwendet, um es maschinenunabhängig zu machen. Folgende Konstruktoren werden verwendet:
      öffentlicher DataInputStream(InputStream in)
        Syntax:   public DataInputStream(InputStream in)   Parameters:   in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream.
      öffentlicher DataOutputStream(InputStream in)
        Syntax:   public DataOutputStream(OutputStream out)   Parameters:   out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream.
    Nach dem Erstellen der Eingabe- und Ausgabestreams verwenden wir die Methoden readUTF und writeUTF der erstellten Streams, um die Nachricht zu empfangen bzw. zu senden.
      public final String readUTF() löst eine IOException aus
      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() löst eine IOException aus
      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. Schließen der Verbindung.

Clientseitige Implementierung

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

Serverseitige Programmierung



Auf der Serverseite sind folgende Schritte erforderlich:
  1. Stellen Sie eine Socket-Verbindung her.
  2. Verarbeiten Sie die vom Kunden kommenden Gleichungen:Auch auf der Serverseite öffnen wir sowohl den InputStream als auch den OutputStream. Nachdem wir die Gleichung erhalten haben, verarbeiten wir sie und geben das Ergebnis durch Schreiben in den OutputStream des Sockets an den Client zurück.
  3. Schließen Sie die Verbindung.

Serverseitige Implementierung

Java-Array initialisieren
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));  }  } } 
Ausgabe:
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. Verwandter Artikel: Einfacher Rechner mit UDP in Java Quiz erstellen