logo

Preprost kalkulator, ki uporablja TCP v Javi

Predpogoj: Programiranje vtičnic v Javi Mreženje se preprosto ne zaključi z enosmerno komunikacijo med odjemalcem in strežnikom. Na primer, razmislite o strežniku za prikaz časa, ki posluša zahteve odjemalcev in odjemalcu odgovori s trenutnim časom. Aplikacije v realnem času za komunikacijo običajno sledijo modelu zahteva-odziv. Odjemalec običajno pošlje objekt zahteve strežniku, ki po obdelavi zahteve pošlje odgovor nazaj odjemalcu. Preprosto povedano, odjemalec zahteva določen vir, ki je na voljo na strežniku, strežnik pa mu odgovori, če lahko preveri zahtevo. Ko na primer po vnosu želenega URL-ja pritisnete enter, se zahteva pošlje ustreznemu strežniku, ki nato odgovori s pošiljanjem odgovora v obliki spletne strani, ki jo brskalniki lahko prikažejo. V tem članku je implementirana aplikacija preprostega kalkulatorja, pri kateri bo odjemalec strežniku poslal zahteve v obliki preprostih aritmetičnih enačb, strežnik pa bo odgovoril z odgovorom na enačbo.

Programiranje na strani odjemalca

Koraki na strani odjemalca so naslednji:
  1. Odprite povezavo vtičnice
  2. Komunikacija:V komunikacijskem delu je manjša sprememba. Razlika v primerjavi s prejšnjim člankom je v uporabi vhodnega in izhodnega toka za pošiljanje enačb in prejemanje rezultatov v strežnik oziroma iz njega. DataInputStream in DataOutputStream se uporabljajo namesto osnovnih InputStream in OutputStream, da postanejo strojno neodvisni. Uporabljajo se naslednji konstruktorji -
      javni DataInputStream(InputStream v)
        Syntax:   public DataInputStream(InputStream in)   Parameters:   in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream.
      javni DataOutputStream(InputStream v)
        Syntax:   public DataOutputStream(OutputStream out)   Parameters:   out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream.
    Po ustvarjanju vhodnih in izhodnih tokov uporabimo readUTF in writeUTF metod ustvarjenih tokov za sprejem oziroma pošiljanje sporočila.
      javni končni niz readUTF() vrže izjemo 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() vrže 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. Zapiranje povezave.

Implementacija na strani odjemalca

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

Programiranje na strani strežnika



Koraki na strani strežnika so naslednji:
  1. Vzpostavite povezavo z vtičnico.
  2. Obdelajte enačbe, ki prihajajo od stranke:Na strani strežnika odpremo tudi inputStream in outputStream. Ko prejmemo enačbo, jo obdelamo in rezultat vrnemo odjemalcu tako, da zapišemo v outputStream vtičnice.
  3. Zaprite povezavo.

Izvedba na strani strežnika

pretvorba niza v int v javi
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));  }  } } 
Izhod:
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. Sorodni članek: Preprost kalkulator z uporabo UDP v Javi Ustvari kviz