반응형
Java Socket Test Example (1) 자바 소켓 예시
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
|
package SocketTest;
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) {
try {
String host;
if (args.length > 0) {
host=args[0];
} else {
host = "localhost";
// host = "172.17.193.68";
}
Socket socket = new Socket(host, 8008);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
// send data to the server
for (int i=1; i<=10; i++) {
System.out.println("Sending: line " + i);
out.println("line " + i);
out.flush();
}
out.println("BYE");
out.flush();
// receive data from the server
while (true) {
String str = in.readLine();
if (str == null) {
break;
} else {
System.out.print(str);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
cs |
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
|
package SocketTest;
import java.io.*;
import java.net.*;
class EchoServer {
public static void main(String[] args) {
System.out.println("EchoServer started.");
try {
ServerSocket s = new ServerSocket(8008);
Socket incoming = s.accept();
System.out.println("Connected to: " + incoming.getInetAddress() +
" at port: " + incoming.getLocalPort());
BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
PrintWriter out = new PrintWriter(new OutputStreamWriter(incoming.getOutputStream()));
out.println("Hello! This is Java EchoServer. Enter BYE to exit.");
out.flush();
for ( ; ; ) {
String str = in.readLine();
if (str == null)
{
break;
}
else
{
out.println("Echo: " + str);
out.flush();
System.out.println("Received: " + str);
if (str.trim().equals("BYE")) {
break;
}
}
}
incoming.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
System.out.println("EchoServer stopped.");
}
}
|
cs |
실행 방법 & 결과
1. javac EchoServer.java (on prompt #01)
2. javac EchoClient.java (on prompt #02)
3. java EchoServer (on prompt #01)
4. java EchoClient (on prompt #02)
반응형
'공부 > Object-Oriented Design Pattern' 카테고리의 다른 글
[OODP] Singleton Pattern (싱글톤 패턴)이란 (0) | 2021.04.04 |
---|---|
Java Socket 메시지 주고받기 (0) | 2021.04.03 |
Java RMI (Remote Method Invocation) (3) (1) | 2021.04.03 |
Java RMI (Remote Method Invocation) (2) (0) | 2021.04.03 |
Java RMI (Remote Method Invocation)을 알아보자 (0) | 2021.04.03 |
댓글