inblog logo
|
hyeonjeong-jang-0302
    JAVA

    전이중 통신(양방향, Full Duplex)

    Jan 10, 2024
    전이중 통신(양방향, Full Duplex)
    💡
    하나씩 해라!!!
     
    1. 서버 생성
    1. 클라이언트 생성
    1. 클라이어트 → 서버 (메시지를 지속적으로 전송)
    1. 서버 → 클라이언트(메시지를 지속적으로 전송)
     

    서버

    package ex17.multi; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.Scanner; public class Server { public static void main(String[] args) { try { // 1. 소켓과 버퍼 만들기 ServerSocket serverSocket = new ServerSocket(20000); Socket socket = serverSocket.accept(); // accept() Scanner sc = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter pw = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8); // 2. 메시지 받기 스레드 new Thread(() -> { while (true) { String requestMsg = null; try { requestMsg = br.readLine(); System.out.println("클라이언트로부터 받은 메시지: " + requestMsg); } catch (IOException e) { e.printStackTrace(); } } }).start(); // 3. 메시지 쓰기 스레드 new Thread(() -> { while (true) { String keyboardMsg = sc.nextLine(); pw.println(keyboardMsg); try { Thread.sleep(500); } catch (InterruptedException e) { throw new RuntimeException(e); } } }).start(); } catch (IOException e) { throw new RuntimeException(e); } } }
     

    클라이언트

    package ex17.multi; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; public class Client { public static void main(String[] args) { try { // 1. 소켓과 버퍼 만들기 Socket socket = new Socket("172.0.0.1", 20000); Scanner sc = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); // 2. 메시지 쓰기 스레드 new Thread(() -> { while (true) { String keyboardMsg = sc.nextLine(); pw.println(keyboardMsg); try { Thread.sleep(500); } catch (InterruptedException e) { throw new RuntimeException(e); } } }).start(); // 3. 메시지 받기 스레드 new Thread(() -> { while (true) { String requestMsg = null; try { requestMsg = br.readLine(); System.out.println("클라이언트로부터 받은 메시지: " + requestMsg); } catch (IOException e) { e.printStackTrace(); } } }).start(); } catch (IOException e) { throw new RuntimeException(e); } } }
    Share article

    hyeonjeong-jang-0302

    RSS·Powered by Inblog