package ch04_quiz;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
/*
* 클라이언트가 서버로 보낸 데이터를 서버가 받아서 더하는 코드를 작성하세요
* 클라이언트로 부터 -(minus) 값이 전송되면 계산을 멈추고 종료합니다
*/
public class CalcServer {
public static void main(String[] args) {
ServerSocket listener = null;
Socket socket = null;
BufferedReader sin = null;
BufferedWriter sout = null;
try {
listener = new ServerSocket(10000);
System.out.println("--- Calc Server ---");
socket = listener.accept();
sin = new BufferedReader(new InputStreamReader(socket.getInputStream()));
sout = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
int res = 0;
int num1 = 0;
int num2 = 0;
int operater = 0;
while(true) {
// 2. 클라이언트에서 값 수신
num1 = sin.read();
num2 = sin.read();
operater = sin.read();
// while문 종료구문
if(num1<0 | num2<0) {
System.out.println("- 연결 종료 -");
break;
}
// 3. 계산 및 데이터 클라이언트에게 전송.
switch(operater) {
case 1:
res = num1+num2;
break;
case 2:
res = num1-num2;
break;
case 3:
res = num1*num2;
break;
case 4:
res = num1/num2;
break;
}
sout.write(res);
sout.flush();
}
} catch (Exception e) {
System.out.println("서버 error");
} finally {
try {
if(sin != null) sin.close();
if(sout != null) sout.close();
if(socket != null) socket.close();
if(listener != null) listener.close();
} catch (Exception e2) {
e2.printStackTrace();;
}
}
} // main
int Calc() {
return 0;
}
}
package ch04_quiz;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;
public class CalcClient {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Socket socket = null;
BufferedReader cin = null;
BufferedWriter cout = null;
try {
socket = new Socket("localhost",10000);
System.out.println("서버 연결...");
cin = new BufferedReader(new InputStreamReader(socket.getInputStream()));
cout = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
int num1 = 0;
int num2 = 0;
int operator = 0;
while(true) {
// 0. 값 입력
System.out.print("num1 > ");
num1 = sc.nextInt();
System.out.print("num2 > ");
num2 = sc.nextInt();
System.out.print("operator 1.+ 2.- 3.* 4./ >");
operator = sc.nextInt();
// while문 종료구문
if(num1 < 0 | num2 <0) {
break;
}
// 1. 서버에 값 송신
cout.write(num1);
cout.write(num2);
cout.write(operator);
cout.flush();
System.out.println();
// 4. 서버에서 값 수신 및 출력
short result = (short) cin.read();
System.out.println("result : " + result);
System.out.println();
}
} catch (Exception e) {
System.out.println("클라이언트 error");
} finally {
try {
if(cin != null) cin.close();
if(cout != null) cout.close();
if(socket != null) socket.close();
if(sc != null) sc.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}