logo

Java'da TCP kullanan Basit Hesap Makinesi

Önkoşul: Java'da Soket Programlama Ağ oluşturma, istemci ile sunucu arasında tek yönlü bir iletişimle sonuçlanmaz. Örneğin, istemcilerin isteklerini dinleyen ve istemciye geçerli saatle yanıt veren bir zaman söyleme sunucusunu düşünün. Gerçek zamanlı uygulamalar genellikle iletişim için istek-yanıt modelini izler. İstemci genellikle istek nesnesini sunucuya gönderir ve sunucu, isteği işledikten sonra yanıtı istemciye geri gönderir. Basit bir ifadeyle, istemci, sunucuda bulunan belirli bir kaynağı talep eder ve sunucu, isteği doğrulayabilirse bu kaynağa yanıt verir. Örneğin istenen URL'yi girdikten sonra enter tuşuna basıldığında, ilgili sunucuya bir istek gönderilir ve sunucu daha sonra tarayıcıların görüntüleyebildiği bir web sayfası biçiminde yanıt göndererek yanıt verir. Bu makalede, istemcinin sunucuya basit aritmetik denklemler şeklinde istek göndereceği ve sunucunun denklemin cevabıyla yanıt vereceği basit bir hesap makinesi uygulaması uygulanmaktadır.

İstemci Tarafı Programlama

İstemci tarafında yer alan adımlar aşağıdaki gibidir:
  1. Soket bağlantısını açın
  2. İletişim:İletişim kısmında ufak bir değişiklik var. Önceki makaleyle arasındaki fark, sırasıyla denklemleri göndermek ve sunucuya ve sunucudan sonuçları almak için hem giriş hem de çıkış akışlarının kullanılmasında yatmaktadır. Veri Giriş Akışı Ve Veri Çıkışı Akışı Makineden bağımsız hale getirmek için temel OutputStream ve OutputStream yerine kullanılır. Aşağıdaki yapıcılar kullanılır -
      genel DataInputStream(InputStream girişi)
        Syntax:   public DataInputStream(InputStream in)   Parameters:   in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream.
      genel DataOutputStream(InputStream girişi)
        Syntax:   public DataOutputStream(OutputStream out)   Parameters:   out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream.
    Giriş ve çıkış akışlarını oluşturduktan sonra, mesajı almak ve göndermek için sırasıyla oluşturulan akış yöntemlerinin readUTF ve writeUTF'lerini kullanırız.
      public final String readUTF(), IOException'ı atar
      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(), IOException'ı atar
      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. Bağlantıyı kapatıyorum.

İstemci Tarafı Uygulaması

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);  }  } } 
Çıkış
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 

Sunucu Tarafı Programlama



Sunucu tarafında yer alan adımlar aşağıdaki gibidir:
  1. Soket bağlantısı kurun.
  2. İstemciden gelen denklemleri işleyin:Sunucu tarafında ayrıca hem inputStream hem de OutputStream'i açıyoruz. Denklemi aldıktan sonra onu işliyoruz ve sonucu soketin çıktıStream'ine yazarak istemciye geri döndürüyoruz.
  3. Bağlantıyı kapatın.

Sunucu Tarafı Uygulaması

manuel test
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));  }  } } 
Çıkış:
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. İlgili Makale: Java'da UDP kullanan Basit Hesap Makinesi Test Oluştur