logo

Yksinkertainen laskin, joka käyttää TCP:tä Javassa

Edellytys: Socket-ohjelmointi Javassa Verkottuminen ei vain päädy yksisuuntaiseen viestintään asiakkaan ja palvelimen välillä. Harkitse esimerkiksi ajan kertovaa palvelinta, joka kuuntelee asiakkaiden pyyntöjä ja vastaa nykyisellä kellonajalla asiakkaalle. Reaaliaikaiset sovellukset noudattavat yleensä pyyntö-vastausmallia viestinnässä. Asiakas lähettää yleensä pyyntöobjektin palvelimelle, joka pyynnön käsittelyn jälkeen lähettää vastauksen takaisin asiakkaalle. Yksinkertaisesti sanottuna asiakas pyytää tiettyä palvelimella olevaa resurssia ja palvelin vastaa siihen, jos se voi tarkistaa pyynnön. Esimerkiksi kun enteriä painetaan halutun URL-osoitteen syöttämisen jälkeen, pyyntö lähetetään vastaavalle palvelimelle, joka sitten vastaa lähettämällä vastauksen verkkosivun muodossa, jonka selaimet pystyvät näyttämään. Tässä artikkelissa on toteutettu yksinkertainen laskinsovellus, jossa asiakas lähettää pyyntöjä palvelimelle yksinkertaisten aritmeettisten yhtälöiden muodossa ja palvelin vastaa vastauksella yhtälöön.

Asiakaspuolen ohjelmointi

Asiakkaan puolella tehtävät vaiheet ovat seuraavat:
  1. Avaa pistorasian liitäntä
  2. Viestintä:Viestintäosassa on pieni muutos. Ero edelliseen artikkeliin on sekä tulo- että lähtövirtojen käytössä yhtälöiden lähettämiseen ja tulosten vastaanottamiseen palvelimelle ja vastaavasti. DataInputStream ja DataOutputStream käytetään perus InputStream ja OutputStream sijasta, jotta se olisi koneriippumaton. Käytössä ovat seuraavat konstruktorit -
      julkinen DataInputStream(InputStream in)
        Syntax:   public DataInputStream(InputStream in)   Parameters:   in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream.
      julkinen DataOutputStream(InputStream in)
        Syntax:   public DataOutputStream(OutputStream out)   Parameters:   out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream.
    Kun tulo- ja lähtövirrat on luotu, käytämme luotujen virtojen menetelmien readUTF- ja writeUTF-koodeja viestin vastaanottamiseen ja lähettämiseen.
      public final String readUTF() heittää IOExceptionin
      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() heittää IOExceptionin
      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. Yhteyden sulkeminen.

Asiakaspuolen toteutus

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);  }  } } 
Lähtö
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 

Palvelinpuolen ohjelmointi



Palvelinpuolen vaiheet ovat seuraavat:
  1. Muodosta pistorasialiitäntä.
  2. Käsittele asiakkaalta tulevat yhtälöt:Palvelinpuolella myös avataan sekä inputStream että outputStream. Saatuamme yhtälön käsittelemme sen ja palautamme tuloksen takaisin asiakkaalle kirjoittamalla socketin outputStreamiin.
  3. Sulje yhteys.

Palvelinpuolen toteutus

merkkijonon alimerkkijono
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));  }  } } 
Lähtö:
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. Aiheeseen liittyvä artikkeli: Yksinkertainen laskin, joka käyttää UDP:tä Javassa Luo tietokilpailu