2권에서 꼭 해보고 싶던 예제.
Server <-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
|
package sec07.exam03_chatting;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class ServerExample extends Application{
ExecutorService executorService;//스레드풀
ServerSocket serverSocket;//서버소켓
List<Client> connections = new Vector<Client>();//클라이언트 컬렉션
void startServer() {
//서버 시작
executorService = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors()
);
try {
serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress("localHost", 5001));
}catch(Exception e) {
if(!serverSocket.isClosed()) {stopServer();} return;
}
Runnable runnable = new Runnable() {
@Override
public void run() {
Platform.runLater( () -> {
displayText("[서버 시작]");
btnStartStop.setText("stop");
});
while(true) {
try {
Socket socket = serverSocket.accept();
String message = "[연결 수락: "+socket.getRemoteSocketAddress()+": "+ Thread.currentThread().getName()+"]";
Platform.runLater(() -> {
displayText(message);
});
Client client = new Client(socket);
connections.add(client);
Platform.runLater(() -> {
displayText("[연결 개수: "+connections.size()+"]");
});
} catch (IOException e) {
if(!serverSocket.isClosed()) {stopServer();} break;
}
}
}
};
executorService.submit(runnable);
}
void stopServer() {
//서버 종료
try {
Iterator<Client> iterator = connections.iterator();
while(iterator.hasNext()) {
Client client = iterator.next();
client.socket.close();
iterator.remove();
}
if(serverSocket !=null && !serverSocket.isClosed()) {
serverSocket.close();
}
if(executorService != null && !executorService.isShutdown()) {
executorService.shutdown();
}
Platform.runLater(() -> {
displayText("[서버 멈춤]");
btnStartStop.setText("start");
});
}catch(Exception e) {}
}
class Client{
Socket socket;
Client(Socket socket){
this.socket = socket;
receive();
}
void receive() {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
while(true) {
byte[] byteArr = new byte[100];
InputStream inputStream = socket.getInputStream();
int readByteCount = inputStream.read(byteArr);
if(readByteCount == -1) {
throw new IOException();
}
String message = "[요청 처리: "+socket.getRemoteSocketAddress()+": "+Thread.currentThread().getName()+"]";
Platform.runLater(() -> displayText(message));
String data = new String(byteArr, 0 , readByteCount, "UTF-8");
for(Client client : connections) {
client.send(data);
}
}
}catch(Exception e) {
try {
connections.remove(Client.this);
String message = "[클라이언트 통신 안됨: "+socket.getRemoteSocketAddress()+": "+Thread.currentThread().getName()+"]";
Platform.runLater(() -> displayText(message));
socket.close();
} catch (IOException e1) {}
}
}
};
executorService.submit(runnable);
}
void send(String data) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
byte[] byteArr = data.getBytes("UTF-8");
OutputStream outputStream = socket.getOutputStream();
outputStream.write(byteArr);
outputStream.flush();
} catch (Exception e) {
try {
String message = "[클라이언트 통신 안됨: "+socket.getRemoteSocketAddress()+": "+Thread.currentThread().getName()+"]";
Platform.runLater(() -> displayText(message));
connections.remove(Client.this);
socket.close();
} catch (IOException e1) {}
}
}
};
executorService.submit(runnable);
}
}
//UI/////////////////////////////////////////////////////////////////////
TextArea txtDisplay;
Button btnStartStop;
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane root = new BorderPane();
root.setPrefSize(500, 300);
txtDisplay = new TextArea();
txtDisplay.setEditable(false);
BorderPane.setMargin(txtDisplay, new Insets(0,0,2,0));
root.setCenter(txtDisplay);
btnStartStop = new Button("start");
btnStartStop.setPrefHeight(30);
btnStartStop.setMaxWidth(Double.MAX_VALUE);
btnStartStop.setOnAction( e -> {
if(btnStartStop.getText().equals("start")) {
startServer();
}else if(btnStartStop.getText().equals("stop")) {
stopServer();
}
});
root.setBottom(btnStartStop);
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("app.css").toString());
primaryStage.setScene(scene);
primaryStage.setTitle("Server");
primaryStage.setOnCloseRequest(e -> stopServer());
primaryStage.show();
}
void displayText(String text) {
txtDisplay.appendText(text+"\n");
}
public static void main(String[] args) {
launch(args);
}
}
|
cs |
Client<-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
|
package sec07.exam03_chatting;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class ClientExample extends Application {
Socket socket;
void startClient() {
//연결 시작 코드
Thread thread = new Thread() {
@Override
public void run() {
try {
socket = new Socket();
socket.connect(new InetSocketAddress("localHost",5001));
Platform.runLater(() -> {
displayText("[연결 완료: "+socket.getRemoteSocketAddress()+"]");
btnConn.setText("stop");
btnSend.setDisable(false);
});
}catch(Exception e) {
Platform.runLater(() -> displayText("[서버 통신 안됨]"));
if(!socket.isClosed()) {stopClient();}
return;
}
receive();
}
};
thread.start();
}
void stopClient() {
//연결 끊기 코드
try {
Platform.runLater(() -> {
displayText("[연결 끊음]");
btnConn.setText("start");
btnSend.setDisable(true);
});
if(socket != null && !socket.isClosed()) {
socket.close();
}
}catch(Exception e) {}
}
void receive() {
//데이터 받기 코드
while(true) {
try {
byte[] byteArr = new byte[100];
InputStream inputStream = socket.getInputStream();
int readByteCount = inputStream.read(byteArr);
if(readByteCount == -1) {
throw new IOException();
}
String data = new String(byteArr, 0, readByteCount, "UTF-8");
//System.out.println(data);
Platform.runLater(() -> displayText(data));
}catch(Exception e) {
Platform.runLater(() -> displayText("[서버 통신 안됨]"));
stopClient();
break;
}
}
}
void send(String data) {
//데이터 전송 코드
Thread thread = new Thread() {
@Override
public void run() {
try {
byte[] byteArr = data.getBytes("UTF-8");
OutputStream outputStream = socket.getOutputStream();
outputStream.write(byteArr);
outputStream.flush();
Platform.runLater(() -> displayText("[보내기 완료]"));
}catch(Exception e) {
Platform.runLater(() -> displayText("[서버 통신 안됨]"));
stopClient();
}
}
};
thread.start();
}
//UI/////////////////////////////////////////////////////////////////////
TextArea txtDisplay;
TextField txtInput;
Button btnConn,btnSend;
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane root = new BorderPane();
root.setPrefSize(500, 300);
txtDisplay = new TextArea();
txtDisplay.setEditable(false);
BorderPane.setMargin(txtDisplay, new Insets(0,0,2,0));
root.setCenter(txtDisplay);
BorderPane bottom = new BorderPane();
txtInput = new TextField();
txtInput.setPrefSize(60, 30);
BorderPane.setMargin(txtInput, new Insets(0,1,1,1));
btnConn = new Button("start");
btnConn.setPrefSize(60, 30);
btnConn.setOnAction( e ->{
if(btnConn.getText().equals("start")) {
startClient();
}else if(btnConn.getText().equals("stop")) {stopClient();}
});
btnSend = new Button("send");
btnSend.setPrefSize(60, 30);
btnSend.setDisable(true);
btnSend.setOnAction(e -> send(txtInput.getText()));
bottom.setCenter(txtInput);
bottom.setLeft(btnConn);
bottom.setRight(btnSend);
root.setBottom(bottom);
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("app.css").toString());
primaryStage.setScene(scene);
primaryStage.setTitle("Client");
primaryStage.setOnCloseRequest(e -> stopClient());
primaryStage.show();
}
void displayText(String text) {
txtDisplay.appendText(text+"\n");
}
public static void main(String[] args) {
launch(args);
}
}
|
cs |
'배운 코드를 적기' 카테고리의 다른 글
JavaFX 로 간단한 app 구현 중. (0) | 2020.06.07 |
---|---|
실습예제 구현하기 (0) | 2020.06.03 |
이것이 자바다 - 04.조건문과 반복문 (0) | 2020.03.25 |