단방향 실습

Jan 09, 2024
단방향 실습
 
💡
서버
package ex17.oneway; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(10000); Socket socket = serverSocket.accept(); // 리스너 (누가 요청하는지 확인) System.out.println("클라이언트 연결됨"); BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream(), "UTF-8") ); while (true) { String msg = br.readLine(); if (msg == null) break; System.out.println(msg); } } catch (IOException e) { throw new RuntimeException(e); } } }
 
💡
클라이언트
package ex17.oneway; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.Socket; public class Client { public static void main(String[] args) { // localhost = 127.0.0.1 (루프백) try { Socket socket = new Socket("127.0.0.1", 10000); // 가나다라abc BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream(), "UTF-8") ); bw.write("msg1" + "\n"); bw.write("msg2" + "\n"); bw.flush(); } catch (IOException e) { e.printStackTrace(); } } }
notion image
Share article

khh