단방향 통신 (Simplex Communication)
- 단방향 통신은 데이터가 한 방향으로만 전송되는 통신 방식을 의미합니다.
- 한 장치가 송신 역할을 하고 다른 장치가 수신 역할을 하며, 데이터는 송신자에서 수신자로만 흐릅니다.
- 텔레비전 방송, 라디오 방송 등이 있습니다.
서버
MyServer
public class MyServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(10000); // 서버소캣 생성
Socket socket = serverSocket.accept();
System.out.println("oh! connect?");
BufferedReader br = new BufferedReader(
// 소켓으로부터 input 받음
new InputStreamReader(socket.getInputStream()) // 버퍼에 소켓 장착
);
String line = br.readLine(); // 버퍼에 있는 메세지를 \n까지 읽는다.
System.out.println("read : " + line);
} catch (Exception e) {
e.printStackTrace();
}
}
}
포트 번호가 있어야 통신이 어디로 가야 하는지 알 수 있습니다.
- ServerSocket은 클라이언트한테서 통신이 들어오면 임시 포트 번호를 부여한 Socket에 배정합니다.
- 소켓은 클라이언트와 1:1로 매칭됩니다.
- 클라이언트와 서버 소켓 사이 연결은 끊어집니다.
클라이언트
MyClient
public class MyClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 10000);
// BufferedWriter bw = new BufferedWriter(
// new OutputStreamWriter(socket.getOutputStream())
// );
//
// bw.write("Hello World\n"); // \n은 붙여야 한다. 프로토콜임
// bw.flush();
// PrintWriter는 BufferedWriter를 더욱 편리하게 쓰기 위해 개발. /n 빼먹어도 괜찮게
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
pw.println("Hello World");
}
}
통신 과정
- 서버의 main을 실행
- 콘솔에 oh! connect? 출력 안 된 상태
- 클라이언트의 main을 실행
- 서버 쪽 콘솔을 보면 oh! connect? 와 read : Hello World 출력

참고: PrintWriter 구조
MyWriter
// Writer
public class MyWriter extends BufferedWriter {
private boolean autoFlush = false;
public MyWriter(OutputStream stream) {
super(new OutputStreamWriter(stream));
}
public MyWriter(OutputStream stream, boolean autoFlush) {
super(new OutputStreamWriter(stream));
this.autoFlush = autoFlush;
}
public void println(String msg) {
try {
this.write(msg);
this.write("\n");
if (autoFlush) {
this.flush();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
- this.write("\n");
- \n을 자동으로 입력해줍니다.
- if (autoFlush) { this.flush(); }
- autoFlush 설정에 따라 .flush() 실행 여부를 선택 가능합니다.
Share article