-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.java
More file actions
91 lines (74 loc) · 2.34 KB
/
Copy pathClient.java
File metadata and controls
91 lines (74 loc) · 2.34 KB
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
package com.javaex.network.v4;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
Socket socket = null;
try {
// 소켓 생성
socket = new Socket();
// 시작 메시지
System.out.println("<클라이언트 시작>");
System.out.println("[연결을 요청합니다.]");
// Connect를 시도
InetSocketAddress remote = new InetSocketAddress("127.0.0.1", 10000);
socket.connect(remote);
System.out.println("[서버에 연결되었습니다]");
// 서버로 메서지를 전송
OutputStream os = socket.getOutputStream();
Writer osw = new OutputStreamWriter(os, "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
InputStream is = socket.getInputStream();
Reader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
// 키보드에서 입력을 받아 봅시다.
BufferedReader keyReader = new BufferedReader(new InputStreamReader(System.in));
while(true) {
String msg = keyReader.readLine();
if (msg.equals("/q")) {
System.out.println("접속을 종료합니다.");
break;
}
bw.write(msg);
bw.newLine();
bw.flush();
System.out.println("전송 메세지:" + msg);
String rcvMsg = br.readLine();
System.out.println("수신 메세지:" + rcvMsg);
}
/*
String msg = "테스트 메세지";
bw.write(msg);
bw.newLine();
bw.flush();
System.out.println("전송 메세지:" + msg);
*/
// Echo Back된 메세지를 받아서 출력
keyReader.close();
br.close();
bw.close();
// 종료
System.out.println("<클라이언트 종료>");
} catch (ConnectException e) {
System.out.println("[접속이 거부되었습니다.]");
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}