logo

Java에서 TCP를 사용하는 간단한 계산기

전제 조건: Java의 소켓 프로그래밍 네트워킹은 클라이언트와 서버 간의 단방향 통신으로 끝나지 않습니다. 예를 들어, 클라이언트의 요청을 듣고 현재 시간으로 클라이언트에 응답하는 시간 알려주는 서버를 생각해 보세요. 실시간 애플리케이션은 일반적으로 통신을 위한 요청-응답 모델을 따릅니다. 클라이언트는 일반적으로 요청을 처리한 후 클라이언트에 응답을 다시 보내는 서버에 요청 개체를 보냅니다. 간단히 말해서 클라이언트는 서버에서 사용 가능한 특정 리소스를 요청하고 서버는 요청을 확인할 수 있으면 해당 리소스에 응답합니다. 예를 들어, 원하는 URL을 입력한 후 Enter 키를 누르면 요청이 해당 서버로 전송된 다음 브라우저가 표시할 수 있는 웹페이지 형식으로 응답을 보내 응답합니다. 이 기사에서는 클라이언트가 간단한 산술 방정식의 형태로 서버에 요청을 보내고 서버가 방정식에 대한 답으로 응답하는 간단한 계산기 응용 프로그램을 구현합니다.

클라이언트측 프로그래밍

클라이언트 측과 관련된 단계는 다음과 같습니다.
  1. 소켓 연결 열기
  2. 의사소통:커뮤니케이션 부분에서는 약간의 변화가 있습니다. 이전 기사와의 차이점은 입력 스트림과 출력 스트림을 모두 사용하여 방정식을 보내고 각각 서버와 결과를 수신한다는 점입니다. 데이터입력스트림 그리고 데이터출력스트림 기본 InputStream 및 OutputStream 대신 사용되어 기계 독립적으로 만듭니다. 다음 생성자가 사용됩니다 -
      공개 DataInputStream(InputStream 입력)
        Syntax:   public DataInputStream(InputStream in)   Parameters:   in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream.
      공개 DataOutputStream(InputStream 입력)
        Syntax:   public DataOutputStream(OutputStream out)   Parameters:   out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream.
    입력 및 출력 스트림을 생성한 후 생성된 스트림 메서드의 readUTF 및 writeUTF를 사용하여 각각 메시지를 수신하고 보냅니다.
      공개 최종 문자열 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 
      공개 최종 문자열 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을 모두 엽니다. 방정식을 받은 후 이를 처리하고 소켓의 출력 스트림에 작성하여 결과를 클라이언트에 다시 반환합니다.
  3. 연결을 닫습니다.

서버측 구현

루프 유형에 대한 Java
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를 사용하는 간단한 계산기 퀴즈 만들기