1. 서버
package ex20.ch03;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
// 전이중 통신 (Full Duflex)
public class MyServer03 {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(20000);
System.out.println("서버 소켓이 대기 중 입니다. 연결을 시도해주세요.");
Socket socket = ss.accept(); // 프로세스 대기 상태
System.out.println("소켓이 연결 되었습니다.");
// 1. 쓰기 분신
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); // 키보드
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
new Thread(() -> {
while (true) {
try {
String reqBody = keyboard.readLine(); // 쓰기 쓰레드 대기 Thread.sleep을 안 쓰는 이유 : 여기서 대기하니까
bw.write(reqBody);
bw.write("\n");
bw.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
// 2. 읽기 분신
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
new Thread(() -> {
while (true) {
try {
String reqBody = br.readLine();
System.out.println("받은 메시지 : " + reqBody);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
2. 클라이언트
package ex20.ch03;
import java.io.*;
import java.net.Socket;
public class MyClient03 {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 20000); // 소켓 연결
// 1. 쓰기 분신
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
new Thread(() -> {
while (true) {
try {
String reqBody = keyboard.readLine();
bw.write(reqBody);
bw.write("\n");
bw.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
// 2. 읽기 분신
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
new Thread(() -> {
while (true) {
try {
String reqBody = br.readLine();
System.out.println("서버로 부터 받은 메시지 : " + reqBody);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Share article