Network Socket Programming java.net.Socket java.net.ServerSocket
Client Socket 클래스 생성자의 인자들: Host 주소 Port 번호 try{ Socket mySock = new Socket(“notborder.org”, 3872); Socket 클래스 생성자의 인자들: Host 주소 Port 번호
mySock.getInputStream(); Client try{ Socket mySock = new Socket(“notborder.org”, 3872); mySock.getInputStream(); Socket 객체의 getInputStream() 메소드는 java.io.InputStream 연결스트림 객체를 돌려줍니다
mySock.getOutputStream(); Client try{ Socket mySock = new Socket(“notborder.org”, 3872); mySock.getOutputStream(); Socket 객체의 getOutputStream() 메소드는 java.io.OutputStream 연결스트림 객체를 돌려줍니다
Reading Byte스트림에서 문자열스트림으로 변환 try{ Socket mySock = new Socket(“notborder.org”, 3872); BufferedReader reader = new BufferedReader(new InputStreamReader(mySock.getInputStream()); Byte스트림에서 문자열스트림으로 변환
Reading
Writing try{ Socket mySock = new Socket(“notborder.org”, 3872); PrintWriter writer = new PrintWriter(mySock.getOutputStream());
Writing try{ Socket mySock = new Socket(“notborder.org”, 3872); PrintWriter writer = new PrintWriter(new BufferedWriter(mySock.getOutputStream()));
Same! Writing writer.write(“hello”); writer.close(); Buffer No Buffer writer.write(“hello”); writer.close(); writer.write(“hello”); writer.close(); Same!
faster! Writing for(int i=0;i<200;i++){ writer.write(“hello”); } Buffer No Buffer for(int i=0;i<200;i++){ writer.write(“hello”); } writer.close(); for(int i=0;i<200;i++){ writer.write(“hello”); } writer.close(); faster!
Server
Server accept() 메소드에서는 클라이언트의 Socket이 연결할 때까지 계속 기다립니다. accept()는 “blocking method”라고 합니다.
Java.net.ServerSocket Java.net.Socket client process server process welcoming socket client socket Java.net.Socket connection socket client process server process
Socket connSock = serverSock.accept(); Client 1 welcoming socket Client 2 Client 3 Socket connSock = serverSock.accept();