logo

Enkel kalkylator med TCP i Java

Nödvändig förutsättning: Socket-programmering i Java Nätverk slutar helt enkelt inte med en enkelriktad kommunikation mellan klienten och servern. Tänk till exempel på en tidsinställningsserver som lyssnar på klienternas begäran och svarar med aktuell tid till klienten. Realtidsapplikationer följer vanligtvis en begäran-svar-modell för kommunikation. Klienten skickar vanligtvis förfrågningsobjektet till servern som efter bearbetning av begäran skickar tillbaka svaret till klienten. Enkelt uttryckt begär klienten en viss resurs tillgänglig på servern och servern svarar på resursen om den kan verifiera begäran. Till exempel när enter trycks in efter att ha angett önskad url skickas en förfrågan till motsvarande server som sedan svarar genom att skicka svaret i form av en webbsida som webbläsarna kan visa. I den här artikeln implementeras en enkel kalkylatorapplikation där klienten skickar förfrågningar till servern i form av enkla aritmetiska ekvationer och servern kommer att svara tillbaka med svaret på ekvationen.

Programmering på klientsidan

Stegen på klientsidan är följande-
  1. Öppna uttagets anslutning
  2. Kommunikation:I kommunikationsdelen sker en liten förändring. Skillnaden mot den föregående artikeln ligger i användningen av både ingångs- och utgångsströmmarna för att skicka ekvationer och ta emot resultaten till respektive från servern. DataInputStream och DataOutputStream används istället för grundläggande InputStream och OutputStream för att göra det maskinoberoende. Följande konstruktörer används -
      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.
    Efter att ha skapat in- och utströmmarna använder vi readUTF och writeUTF för de skapade strömmetoderna för att ta emot respektive skicka meddelandet.
      public final String readUTF() kastar 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() kastar 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. Stänger anslutningen.

Implementering på klientsidan

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

Programmering på serversidan



Steg involverade på serversidan är följande-
  1. Upprätta en uttagsanslutning.
  2. Bearbeta ekvationerna som kommer från klienten:På serversidan öppnar vi också både inputStream och outputStream. Efter att ha mottagit ekvationen bearbetar vi den och returnerar resultatet tillbaka till klienten genom att skriva på outputStream av socket.
  3. Stäng anslutningen.

Implementering på serversidan

linux byta namn på katalogen
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));  }  } } 
Produktion:
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. Relaterad artikel: Enkel kalkylator med UDP i Java Skapa frågesport