logo

JavaでTCPを使用した簡単な計算機

前提条件: Java でのソケット プログラミング ネットワーキングは、クライアントとサーバー間の一方向通信だけでは終わりません。たとえば、クライアントのリクエストをリッスンし、現在の時刻をクライアントに応答する時刻通知サーバーを考えてみましょう。リアルタイム アプリケーションは通常、通信の要求/応答モデルに従います。通常、クライアントはリクエスト オブジェクトをサーバーに送信し、サーバーはリクエストの処理後に応答をクライアントに送り返します。簡単に言うと、クライアントはサーバー上で利用可能な特定のリソースを要求し、サーバーはその要求を検証できればそのリソースに応答します。たとえば、目的の URL を入力した後に Enter キーを押すと、対応するサーバーにリクエストが送信され、サーバーはブラウザーが表示できる Web ページの形式で応答を送信して応答します。この記事では、クライアントが単純な算術方程式の形式でサーバーにリクエストを送信し、サーバーがその方程式に対する答えを返す単純な計算アプリケーションが実装されています。

クライアント側プログラミング

クライアント側で必要な手順は次のとおりです。
  1. ソケット接続を開きます
  2. コミュニケーション:通信部分に若干の変更があります。前回の記事との違いは、入力ストリームと出力ストリームの両方を使用して、サーバーとの間で方程式を送信し、結果を受信することにあります。 データ入力ストリーム そして データ出力ストリーム マシンに依存しないようにするために、基本的な InputStream と OutputStream の代わりに使用されます。次のコンストラクターが使用されます -
      public DataInputStream(入力ストリーム)
        Syntax:   public DataInputStream(InputStream in)   Parameters:   in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream.
      public DataOutputStream(入力ストリーム)
        Syntax:   public DataOutputStream(OutputStream out)   Parameters:   out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream.
    入力ストリームと出力ストリームを作成した後、作成されたストリーム メソッドの readUTF と writeUTF を使用して、それぞれメッセージを受信および送信します。
      public Final String readUTF() が 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() が 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. 接続を閉じます。

クライアント側の実装

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);  }  } } 
出力
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 

サーバーサイドプログラミング



サーバー側で必要な手順は次のとおりです。
  1. ソケット接続を確立します。
  2. クライアントから受け取った方程式を処理します。サーバー側でも、inputStreamとoutputStreamの両方を開きます。方程式を受け取った後、それを処理し、ソケットのoutputStreamに書き込むことで結果をクライアントに返します。
  3. 接続を閉じます。

サーバー側の実装

文字列をjsonオブジェクトに変換
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));  }  } } 
出力:
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. 関連記事: Java で UDP を使用した簡単な計算機 クイズの作成