35.전이중

Jan 10, 2024
35.전이중
notion image
💡
1.서버 생성 2.클라이언트 생성 3.클 -> 서버 (메세지를 지속적으로 전송) 4.서버 → 클 (메세지를 지속적으로 전송)
서버 클라이언트 순서 할 거 없이 본인들이 먼저 데이터를 보내고 싶을 때 보내는 것
예제
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 Clienet { public static void main(String[] args) { try { //1. 소켓과 버퍼 만들기 Socket socket = new Socket("192.168.0.43",20000); Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(socket.getOutputStream(),true); BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream()) ); //2. 메세지 전송 스레드 new Thread(() -> { while (true){ String a = sc.nextLine(); pw.println(a); } }).start(); //3. 메시지 읽기 스레드 new Thread(() -> { while (true) { String requestMsg = null; try { requestMsg = br.readLine(); System.out.println("서버로부터 받은 메시지 : " + requestMsg); } catch (IOException 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.ServerSocket; import java.net.Socket; import java.nio.charset.Charset; import java.util.Scanner; //동기적 실행 public class Server { public static void main(String[] args) { try { //1. 소켓과 버퍼 만들기 ServerSocket serverSocket = new ServerSocket(20000); Socket socket = serverSocket.accept(); // 소켓 연결 완료됨 Scanner sc = new Scanner(System.in); // 버퍼 만들기 (recevied) BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream()) ); //버퍼 만들기 (sand) PrintWriter pw = new PrintWriter(socket.getOutputStream(),true); //메세지 받기 스레드 new Thread(() -> { while (true) { String requestMsg = null; try { requestMsg = br.readLine(); System.out.println("클라이언트로부터 받은 메시지 : " + requestMsg); } catch (IOException e) { throw new RuntimeException(e); } } }).start(); // 메세지 보내기 스레드 new Thread(() -> { while (true){ String a = sc.nextLine(); pw.println(a); } }).start(); } catch (IOException e) { throw new RuntimeException(e); } } }
 
Share article

More articles

See more posts
RSSPowered by inblog