Skip to content

Commit da604ba

Browse files
committed
add examples for multi-thread.
1 parent 06a6037 commit da604ba

2 files changed

Lines changed: 95 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.eomjinyoung.lesson01.exam02.multiserver;
2+
3+
import java.net.ServerSocket;
4+
import java.net.Socket;
5+
6+
public class CalculatorServer {
7+
private int port;
8+
9+
public CalculatorServer(int port) {
10+
this.port = port;
11+
}
12+
13+
public void service() throws Exception {
14+
ServerSocket serverSocket = new ServerSocket(port);
15+
System.out.println("CalculatorServer startup:");
16+
17+
Socket socket = null;
18+
19+
while(true) {
20+
try {
21+
System.out.println("waiting client...");
22+
23+
socket = serverSocket.accept();
24+
System.out.println("connected to client.");
25+
26+
new CalculatorWorker(socket).start();
27+
28+
} catch (Throwable e) {
29+
System.out.println("connection error!");
30+
}
31+
}
32+
33+
}
34+
35+
public static void main(String[] args) throws Exception {
36+
CalculatorServer app = new CalculatorServer(8888);
37+
app.service();
38+
}
39+
}
40+
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package com.eomjinyoung.lesson01.exam02.multiserver;
2+
3+
import java.io.PrintStream;
4+
import java.net.Socket;
5+
import java.util.Scanner;
6+
7+
public class CalculatorWorker extends Thread {
8+
static int count;
9+
10+
Socket socket;
11+
Scanner in;
12+
PrintStream out;
13+
14+
public CalculatorWorker(Socket socket) throws Exception {
15+
count++;
16+
this.socket = socket;
17+
in = new Scanner(socket.getInputStream());
18+
out = new PrintStream(socket.getOutputStream());
19+
}
20+
21+
@Override
22+
public void run() {
23+
System.out.println("[thread-" + count + "] processing the client request.");
24+
25+
String operator = in.nextLine();
26+
double a = Double.parseDouble(in.nextLine());
27+
double b = Double.parseDouble(in.nextLine());
28+
double r = 0;
29+
30+
try {
31+
switch (operator) {
32+
case "+": r = a + b; break;
33+
case "-": r = a - b; break;
34+
case "*": r = a * b; break;
35+
case "/":
36+
if (b == 0) throw new Exception("0 으로 나눌 수 없습니다!");
37+
r = a / b; break;
38+
default:
39+
throw new Exception("해당 연산을 지원하지 않습니다!");
40+
}
41+
out.println("success");
42+
out.println(r);
43+
44+
} catch (Exception err) {
45+
out.println("failure");
46+
out.println(err.getMessage());
47+
}
48+
49+
try { out.close(); } catch (Exception e) {}
50+
try { in.close(); } catch (Exception e) {}
51+
try { socket.close(); } catch (Exception e) {}
52+
53+
System.out.println("[thread-" + count + "] closed client.");
54+
}
55+
}

0 commit comments

Comments
 (0)