Java - GUI를 활용한 간단한 1:1채팅서버

2020. 7. 30. 21:06Java

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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
package chat;
 
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
 
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.JScrollPane;
 
public class SimpleChatServer extends JFrame {
    private JTextField textField;
    JTextArea textArea;
    JLabel lblStatus;
    private ServerSocket serverSocket;
    private Socket socket;
 
    private DataInputStream dis;
    private DataOutputStream dos;
 
    private boolean connectStatus;// 클라이언트 접속 여부 저장
    private boolean stopSignal;// 쓰레드 종료 신호 저장
 
    private String password = "1234";// 클라이언트에서 접속용으로 사용할 패스워드
 
    public SimpleChatServer() {
        showFrame();
        startService();// 채팅 서버 시작
    }
 
    public void showFrame() {
        setTitle("1:1 채팅 서버");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(400400500300);
        getContentPane().setLayout(null);
 
        textArea = new JTextArea();
        textArea.setEditable(false);
        textArea.setBackground(Color.LIGHT_GRAY);
        getContentPane().add(textArea);
 
        textField = new JTextField();
        textField.setBounds(023039031);
        getContentPane().add(textField);
        textField.setColumns(10);
 
        JButton btnInput = new JButton("입력");
        btnInput.setBackground(Color.YELLOW);
        btnInput.setForeground(Color.BLUE);
        btnInput.setBounds(3872309731);
        getContentPane().add(btnInput);
 
        JPanel panel = new JPanel();
        panel.setBounds(0048422);
        getContentPane().add(panel);
 
        lblStatus = new JLabel("클라이언트 연결 상태 : 연결없음");
        lblStatus.setForeground(Color.RED);
        panel.add(lblStatus);
        
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(023484208);
        getContentPane().add(scrollPane);
        scrollPane.setViewportView(textArea);
 
        textField.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });
 
        setVisible(true);
 
        textField.requestFocus();
 
    }
 
    public void startService() {
        try {
            textArea.append("채팅 서비스 준비중..\n");
 
            // ServerSocket 객체를 생성하여 지정된 포트(59876)를 개방
            serverSocket = new ServerSocket(59876);
            textArea.append("서비스 준비 완료\n");
 
            // 클라이언트로부터 접속이 성공할 때까지 접속 무한 대기
            connectStatus = false;
            while (!connectStatus) {
                textArea.append("클라이언트 접속 대기중...\n");
                // ServerSocket 객체의 accept()메서드를 호출하여 연결대기
                // 연결 완료 시 Socket 객체 리턴됨
                socket = serverSocket.accept();
                // 접속된 클라이언트에 대한 IP 주소 정보 출력
                textArea.append("클라이언트가 접속 하였습니다. (" + socket.getInetAddress() + ")\n");
 
                // DataInputStream 객체 생성 후 입력되는 패스워드 가져와서 출력
 
                dis = new DataInputStream(socket.getInputStream());
 
                String clientPass = dis.readUTF();
//            System.out.println("전달된 패스워드 : "+pass);
                textArea.append("접속된 비밀번호 : " + clientPass + "\n");
 
                // DataOutStream 객체 생성
 
                dos = new DataOutputStream(socket.getOutputStream());
 
                // 입력받은 패스워드와 저장된 패스워드 비교
                if (!clientPass.equals(password)) {// 일치하지 않는 경우
//                dos.writeUTF("패스워드 불일치");
                    dos.writeBoolean(false);
                    textArea.append("클라이언트 패스워드 불일치로 접속 해제됨\n");
                }else {
                    connectStatus=true;
                    textArea.append("클라이언트 패스워드 일치\n");
                    lblStatus.setText("클라이언트 연결 상태 : 연결됨");
                    dos.writeBoolean(true);
                }
            }
            
            //Runnable 인터페이스를 구현하여 Thread 객체에 전달 후 start() 메서드 호출
            //바로 쓰레드 실행까지 처리됨
            new Thread(new Runnable() {
                
                @Override
                public void run() {
                    //클라이언트로부터 전송되는 메세지를 처리할 receiveMessage() 메서드 호출
                    receiveMessage();
                }
            }).start();
 
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
    
    public void receiveMessage() {
        //멀티 쓰레딩으로 메세지 수신 처리 작업 수행
        //boolean 타입 멤버변수 stopSignal 이 false 일 동안 반복해서 메세지 수신
        
        try {
            while(!stopSignal) {
                //클라이언트가 writeUTF() 메서드로 전송한 메세지를 입력받기
                textArea.append("클라이언트 : "+dis.readUTF()+"\n");
            }
            //stopSignal 이 true 가 되면 메세지 수신 종료되므로 dis와 socket 반환
            dis.close();
            socket.close();
        }catch(EOFException e){
            //상대방이 접속 해제할 경우 소켓이 제거되면서 호출되는 예외
            textArea.append("클라이언트 접속이 해제되었습니다.\n");
            lblStatus.setText("클라이언트 연결 상태 : 미연결");
            connectStatus=false;
        }catch(SocketException e) {
            textArea.append("서버 접속이 해제되었습니다.\n");
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        
        
        
    }
    
 
    public void sendMessage() {
        try {
            String text = textField.getText();
            textArea.append(text + "\n");
            
            //입력된 메세지가 "/exit" 일 경우
            if(text.equals("/exit")) {
                //textArea 에 "bye" 출력 후
                //stopSignal을 true로 설정 , 스트림 반환, 소켓 반환
                stopSignal=true;
                dos.close();
                socket.close();
                
                //프로그램 종료
                System.exit(0);
            }else {
                //입력된 메세지가 "/exit"가 아닐 경우( 전송할 메세지인 경우)
                //클라이언트에게 메세지 전송
                dos.writeUTF(text);
                
                //초기화 및 커서요청
                textField.setText("");
                textField.requestFocus();
                
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        new SimpleChatServer();
    }
}
 
package chat;
 
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
 
public class SimpleChatClient extends JFrame {
    private JTextField textField;
    JTextArea textArea;
    JLabel lblStatus;
    private Socket socket;
 
    private DataInputStream dis;
    private DataOutputStream dos;
 
    private boolean connectStatus;// 클라이언트 접속 여부 저장
    private boolean stopSignal;// 쓰레드 종료 신호 저장
 
    public SimpleChatClient() {
        showFrame();
    }
 
    public void showFrame() {
        setTitle("1:1 채팅 클라이언트");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(1200400500300);
        getContentPane().setLayout(null);
 
        textArea = new JTextArea();
        textArea.setEditable(false);
        textArea.setBackground(Color.LIGHT_GRAY);
        getContentPane().add(textArea);
 
        textField = new JTextField();
        textField.setBounds(023039031);
        getContentPane().add(textField);
        textField.setColumns(10);
 
        JButton btnInput = new JButton("입력");
        btnInput.setForeground(Color.BLUE);
        btnInput.setBackground(Color.YELLOW);
        btnInput.setBounds(3872309731);
        getContentPane().add(btnInput);
 
        JPanel panel = new JPanel();
        panel.setBounds(0048422);
        getContentPane().add(panel);
        
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(023484208);
        getContentPane().add(scrollPane);
        scrollPane.setViewportView(textArea);
        
 
        lblStatus = new JLabel("서버 연결 상태 : 미연결");
        lblStatus.setForeground(Color.RED);
        panel.add(lblStatus);
 
        textField.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });
 
        setVisible(true);
        
 
        startService();
        
        textArea.requestFocus();// 텍스트필드에 커서요청
 
    }
    public void startService() {
//        서버접속시도
        String password= prepareConnect();
        boolean connectResult=connectServer(password);
        
        //서버접속 결과 판별하여 패스워드 일치할 때까지 패스워드 입력 후 접속 시도
        while(!connectResult) {
            
            password=prepareConnect();
            connectResult=connectServer(password);
            
        }
        textArea.append("서버접속 패스워드 일치\n");
        
        //멀티쓰레딩 구현하여 receiveMessage() 메서드 호출
        
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                receiveMessage();
            }
        }).start();
        
        
    }
    
 
    public String prepareConnect() {
        // 서버접속을 위한 패스워드 입력
        // 아무입력없이 확인을 눌렀을 경우("" 입력시)
        // 다이얼로그를 사용하여 "패스워드 입력 필수!" 출력 후 다시 입력 받기
        // 단, password가 null이 아닐 때만 판별 수행
        String password = JOptionPane.showInputDialog(this"패스워드 입력");
 
        while (password != null && password.equals("")) {
            JOptionPane.showMessageDialog(this"패스워드 입력 필수!""경고", JOptionPane.ERROR_MESSAGE);
            password = JOptionPane.showInputDialog(this,"패스워드 입력");
            
        }
 
        // 취소 버튼 눌렀을 경우 (null 입력 시)
        // ConfurmDialog를 사용하여 "종료하시겠습니까?" 질문에 예/아니오 선택받기
        if (password == null) {
            int confirm = JOptionPane.showConfirmDialog(this"종료하시겠습니까?""종료 확인", JOptionPane.YES_NO_OPTION);
//                    System.out.println(confirm);
            // 선택된 버튼의 값을 JOptionPane.XXX_OPTION 상수와 비교
            if (confirm == JOptionPane.YES_OPTION) {// 예(Y) 선택 시 현재 프로그램 종료
                System.exit(0);// 프로그램 강제 종료(정상적인 강제 종료)
                
            }
            
            return null;
        }
        //----------------------------------------
 
        return password;
    }
 
    public boolean connectServer(String password) {
 
        try {
            textArea.append("서버에 접속을 시도 중입니다....\n");
 
            // socket 객체를 생성하여 IP 주소와 포트번호 전달->서버 접속시도
            socket = new Socket("localhost"59876);
 
            // DataOutputStream 객체 생성 후 입력되는 패스워드 넘겨주기
 
            dos = new DataOutputStream(socket.getOutputStream());
            dos.writeUTF(password);
 
            textArea.append("서버 접속 완료\n");
 
            textArea.append("패스워드 확인중...\n");
 
            // DataInputStream 객체 생성 후 전달받은 접속요청 결과 출력
            dis = new DataInputStream(socket.getInputStream());
            boolean result = dis.readBoolean();
            
            //전달받은 접속요청 결과 판별
            if(!result) {
                textArea.append("패스워드 불일치로 연결 실패\n");
                socket.close();//소켓 반환
                return false;
            }else {
                lblStatus.setText("서버 연결 상태 : 연결됨\n");
                connectStatus=true;
            }
 
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return true;
    }
    
    public void receiveMessage() {
        //멀티 쓰레딩으로 메세지 수신 처리 작업 수행
        //boolean 타입 멤버변수 stopSignal 이 false 일 동안 반복해서 메세지 수신
        
        try {
            while(!stopSignal) {
                //클라이언트가 writeUTF() 메서드로 전송한 메세지를 입력받기
                textArea.append("서버 : "+dis.readUTF()+"\n");
            }
            //stopSignal 이 true 가 되면 메세지 수신 종료되므로 dis와 socket 반환
            dis.close();
            socket.close();
        }catch(EOFException e){
            //상대방이 접속 해제할 경우 소켓이 제거되면서 호출되는 예외
            textArea.append("서버 접속이 해제되었습니다.\n");
            lblStatus.setText("서버 연결 상태 : 미연결");
            connectStatus=false;
        }catch(SocketException e) {
            textArea.append("서버 접속이 해제되었습니다.\n");
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        
        
        
    }
    
 
    public void sendMessage() {
        try {
            String text = textField.getText();
            textArea.append(text + "\n");
            
            //입력된 메세지가 "/exit" 일 경우
            if(text.equals("/exit")) {
                //textArea 에 "bye" 출력 후
                //stopSignal을 true로 설정 , 스트림 반환, 소켓 반환
                stopSignal=true;
                dos.close();
                socket.close();
                
                //프로그램 종료
                System.exit(0);
            }else {
                //입력된 메세지가 "/exit"가 아닐 경우( 전송할 메세지인 경우)
                //클라이언트에게 메세지 전송
                dos.writeUTF(text);
                
                //초기화 및 커서요청
                textField.setText("");
                textField.requestFocus();
                
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        new SimpleChatClient();
    }
}
 
 
cs

 

Server와 Client의 개념을 이용해서 간단한 1:1 채팅 프로그램을 만들어보았다. 

필요하다 싶은 기능들을 하나씩 만들어가면서 나가니깐 흥미로웠다. 

개념이 어려운건 없었고 간단하게 생각하고 넘어갔던 문법들이 하나씩 나오니까 기억해내지 못해서 아쉬웠다.

다음에는 이런일이 없도록 복습을 제대로 해야 하겠다. 그리고 멤버 변수로 선언을 해주고 나서 로컬 변수에서도 새로 선언을 해주니 자꾸 NullpointException 이 나와서 고생했는데 너무 간단하지만 그냥 넘어가기 쉬우니깐 꼼꼼하게 

잘 확인 하도록 해야 하겠다.