본문 바로가기
개발 관련/JAVA 수업

IO 스트림, 네트워크 - 19일차

by 달달한 강냉이 2011. 10. 5.

InputStreamReader와 OutputStreamWriter
 InputStreamReader :
  Byte Input Stream=>Character Input Stream
 OutputStreamWriter
 Byte Output Stream = > Character Output Stream


Scanner(이미지 텍스트 등을 스캔한다. 그내용을 읽어드려서 스캔한다는 내용) java.util에서 제공
 JDK 5.0에서는 java.util package에 Scanner class를 제공.
 Scanner class는 Input 값(Character열, file, Input Stream)을 정규 표현식으로 구분하여 Character열이나 기본 Data type으로 token 할 수 있는 class이다.
 정규 표현식이란 Language을 표현 할 수 있는 Character식을 말한다.

 http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html

 이렇게 구분된 token은 다양한 nextXXX() method를 사용하여 다른 type의 값으로 바뀌게 된다.


Keyboard로 Input(입력)한 값을 int(정수)로 변환한 예
 Scanner scan = new Scanner(System.in);
 int _int = scan.nextInt();


File class를 이용한 double로 변환한 예
 Scanner scan = new Scanner(new File(“c:\\scan.txt”));
 while( scan.hasNextDouble()){
 long _long = scan.nextDouble();
 }

 


Character열을 구분 패턴으로 변환한 예
//아래예제는 그냥 구분해서 보여주는 예제

String str = “1 and 2 and animal and lion and tiger”;
Scanner scan = new Scanner(str);
scan.useDelimeter(“\\s*and\\s*”); // useDelimeter () 나누는 스플리쉬랑 스플링 토큰 나이저같은 조건따라 나누어주는 기능
int firstToken = scan.nextInt(); // 앞의 조건에따라 구분해서 나누어서 보여준다.
int secondToken = scan.nextInt();
int thirdToken = scan.next();
int fourthToken = scan.next();
int fifthToken = scan.next();

“\\s*and\\s*” => and 앞뒤로 있는 0개 이상의 빈 공백을 의미한다.

 

Stream(기본적으로 인풋과 같은 것이 읽어드리는 작업을 하지만 스캔을 쓰면 더빠르고 정확하게 읽어드리는것이 가능하다.)을 이용한 구분 패턴으로 변환한 예

URLConnection urlCon =
 new URL(“http://www.sist.co.kr”).openConnection();
Scanner scan = new Scanner(urlCon.getInputStream());
scan.useDelimiter(“\\Z”);
String text = scan.next();
System.out.println(text);

“\\Z” => 문서의 끝을 의미한다.

 


※ Scanner의 주요 생성자

Scanner(File source) : 매개변수 File 객체인 source로 Scanner 객체를 생성한다.이 생성자는 FileNotFoundException 예외를 발생한다.


Scanner(InputStream source) : 매개변수 InputStream 객체인 source로 Scanner 객체를 생성한다.

 

--------------------------------
--------------------------------


[ScannerConsoleEx.java]
import java.util.*;
public class ScannerConsoleEx {
 public static void main(String[] args){
  System.out.print("입력 : ");
  Scanner scan = new Scanner(System.in);
  int number = scan.nextInt(); //정수를 뽑아옵니다. 정수를 넣는다 했기 때문에 다른것을 넣으면  오류발생  nextInt(); 말고 String s = scan.next(); 라고 쓰면 문자열을 받아드린다.scan.next();
  System.out.printf("스캔 : %d", number);
  scan.close();
 }
}

//%d 숫자열. %s문자열을 받는다.
--------------------------------
--------------------------------


//아래의 예제는 더블혀이 아니면 출력물이 나오는것이없다.
[ScannerFileEx.java]
import java.util.*;
import java.io.*;
public class ScannerFileEx {
 public static void main(String[] args) {
  Scanner scan = null; //스캐너 객체 선언
  try {
   scan = new Scanner(new File("c:\\scan.txt")); //트라이블록에서 스캐너 객체 생성 파일객체는 c:\\scan.txt"를 읽는다.
   while (scan.hasNextDouble()) { // while(scan.hasNext()){더블형 부분을 이와 같이 문자열로 바꿔주면 문자열은 나온다. // 와일문에 이메소드가 있으면 hasNextDouble() 헤즈 넥스트 더블 메소드는 더블형 데이터가 있으면 트루 없으면 ㅂ펄스    더블형의 데이터가 있으면 이 밑에줄을 읽는다. 그러니 실행시키고 숫자를 입력하면 실행이 되나. 문자를 입력할경우 입력한것만 나오고 밑에줄은 읽지 않는 것을 알수 있다.
    System.out.printf("스캔 double : %,.2f %n" , // System.out.printf("스캔 double : %s %n",이부분도 문자열을 뽑을땐 이와같이 수정 //  %,.2f 이거는 플롯형으로 소수점 끝에가 두자리까지 나타낸다.  %,5.2f 이렇게 할경우 앞에는 다섯자리 뒤에는 두자리 까지만 나타낸다. 라는 뜻.
      scan.nextDouble()); //더블형 데이터를 와일문으로 읽어드린다.
   }
   scan.close();
  } catch (IOException ioe) {
   ioe.printStackTrace();

   } finally {
   if (scan != null)
    scan.close();
  }
 }
}


--------------------------------
--------------------------------
[ScannerReadableEx.java]
import java.io.*;
import java.util.*;
public class ScannerReadableEx {
 public static void main(String[] args) {
  Scanner scan = null;
  FileReader fr = null;
  try {
   fr = new FileReader("c:\\scan.txt"); // 파일 리더 객체 생성 "c:\\scan.txt" 요거 읽어라. 위에 예제는 new Scanne 를 이용 이건 파일 리더를 이용해서. 결과 실행동작은 똑같다.
   scan = new Scanner(fr);
   while (scan.hasNextDouble()) {
    System.out.printf("스캔 double : %,.2f %n" ,
      scan.nextDouble());
   }
  } catch (IOException ioe) {
   ioe.printStackTrace();
  } finally {
   try {
    if (fr != null) fr.close();
   } catch (IOException ioe) {
    ioe.printStackTrace();
   }
   if (scan != null) scan.close();
  }
 }
}
--------------------------------
--------------------------------

//띄워쓰기 기준으로 해서 뽑아낼떄 쓴 예제

[ScannerRegEx.java]
import java.util.*;
public class ScannerRegEx {
 public static void main(String[] args){
  String str = "1 and 2  and  animal  and lion and tiger";
  Scanner scan = new Scanner(str);
  scan = scan.useDelimiter("\\s*and\\s*"); // ("\\s*and\\s*"); 엔드의 앞뒤 여백을 가지고 구분한다.
  int firstToken = scan.nextInt(); // 1, 2를 끄집어낼떄는 int를 써서 끄집어냈고
  int secondToken = scan.nextInt();
  String thirdToken = scan.next(); // 뒤에 있는 문자를 끄집어 낼때는 넥스트를 이용해서 끄집어냈음
  String fourthToken = sca next();
  String fifthToken = scan.next();
  System.out.printf("%d,%d,%s,%s,%s",firstToken,
    secondToken,thirdToken,fourthToken,fifthToken);
  scan.close();
 }
}
--------------------------------
--------------------------------
//외부에 있는 내용을 읽어왔는지 한번 확인해보면 된다. 읽으면 소스값을 받아온것을 확인할수 있을것이다.

[ScannerURLConnectionEx.java]
import java.net.*;
import java.io.*;
import java.util.*;
public class ScannerURLConnectionEx {
 public static void main(String[] args) {
  URLConnection urlCon = null; //URLConnection   // URLConnection 유알엘 커넥션 객체생성
  Scanner scan = null;
  try {
   urlCon = new URL("http://java.sun.com/j2se/1.5.0/docs/api/" +
          "index.html").openConnection(); // openConnection(); 오픈 커넥션 → URL("http://java.sun.com/j2se/1.5.0/docs/api/" + "index.html") 를 가져와라?
   scan = new Scanner(urlCon.getInputStream()); // URL에 있는것을 가져와서 읽어라.
   scan.useDelimiter("\\Z");
   String text = scan.next();
   System.out.println(text);
  } catch (IOException e) {
   e.printStackTrace();
  } finally{
   if (scan != null) scan.close();
  }
 }
}

--------------------------------
--------------------------------
Object의 직렬화(객체 직렬화)
 Object의 직렬화란 Object를 Stream으로 file에 저장하는 방법.(저장하고 읽어오는)
 Object를 직렬화하기 위한 두 가지 방법으로 Serializable과 Externalizable Interface 구현하면 된다.

Serializable 시리얼 나이즈
 Serializable Interface를 구현한 class를 작성하면 해당 class의 모든 Member변수가 직렬화 대상이 된다.
 Object가 Stream을 통해 직렬화 될 때는 Object에 있는 Member변수가 직렬화 되는 것이다.
 Object의 Member변수 중에 직렬화 대상에 제외하고 싶다면 transient Keyword를 사용하면 된다. (직렬대상에 제외하겠다는 이야기는 파일에 쓰지 않겠다는 이야기다.)
  public transient int age;

 

Externalizable 이스터널 나이즈
 Externalizable Interface는 Serializable Interface의 Sub Interface이다.

Public interface Externalizabel extends Serializable{
 public void readExternal(ObjectInput in) throws
  IOException,ClassNotFoundException;
 public void writeExternal(ObjectOutput out) throws
  IOExcepiton;
}//특정한 멤버변수만 직렬화 하기 위해서 //시리얼 나이즈와 이스터널 나이즈를 구현만 하면 직렬화가된다. 이스터널 나이즈가 좀더다양
Externalizable Interface를 구현한 class는 위의 두 가지 method를 이용하여 특정 Member 변수만을 직렬화 할 수 있는 기능을 제공한다.

ObjectOutputStream(객체를 쓰는거) 오브젝트 아웃풋 스트림

ObjectInputStream(객체를 읽어오는거)


StreamTokenizer(스트림 토크나이저 : 문자 인풋스트림을 토큰 단위로 나뉘어서 관리) //네트워크나 파일을 통해서 주고받을때
 Character Input Stream을 token 단위로 나눠서 관리할 수 있는 class이다.
 Character Input Stream을 읽을 때 token의 유형을 Character와 숫자로 구분할 수 있기 때문에 Character와 숫자로 구성된 file을 읽을 유용하게 쓰일 수 있다.


RandomAccessFile(랜덤액세스파일) : 입력과 출력 두가지 기능을 다할수 있다.
 Input Stream과 Output Stream의 두가지 기능을 가지고 있는 Stream이며, 기존의 Input Stream과 달리 한 번 읽었던 Input Stream을 다시 읽을 수 있는 Stream이다.


지금은 단방향밖에 안되나, 나중에보면 엔아이오라고해서 양방향이 가능한것이 있다. 채널을 이용해서.(그러나 양방향이 나와있지만 아직도 아이오로 작업한다.)


Stream의 정의와 특징을 배운다.
File class의 사용방법과 활용 방법을 배운다.
Byte Stream의 종류와 사용 방법을 배운다.
Character Stream의 종류와 사용 방법을 배운다.


제일중요한건 위의 네가지고 나머지는 필요에 의해서하는거다.

 


--------------------------------
--------------------------------
//바이트 스트림을 읽어서 캐리터 스트림을 바꾸는 예제

[InOutStreamReaderEx.java]
import java.io.*;
public class InOutStreamReaderEx {
 public static String consoleInput(String input)
 throws IOException{
  System.out.print(input+" : ");
  InputStreamReader isr = new InputStreamReader(
    System.in); //바이터스트림으로 읽을것을
  BufferedReader br = new BufferedReader(isr);
  String message = br.readLine();
  return message;
 }
 public static void main(String[] args) throws IOException{
  String id  = consoleInput("id");
  String password  = consoleInput("password");
  OutputStreamWriter out =
   new OutputStreamWriter(System.out); // System.out표준출력하는걸만들어주고
  out.write("id : "+ id + " , password : "+password);
  out.close();
 }
}
//괜히ㅗ 되게 복잡하게 만든 예쩨

--------------------------------
--------------------------------
//객체 직렬화. 객체에 있는 멤버변수의 값을 갖다쓰나 갖다 쓰고 싶은것만 갖다쓰는 경우를 말함.   Externalizable이스터널 라이즈 너블
//이터널 라이즈 나 시리얼 라이즈나 둘중에 암거나 하나 알면댐..

[ExternalizableEx.java]
import java.io.*;
public class ExternalizableEx implements Externalizable {
 private String name; // 세개의 멤버변수 선언
 private int age;
 private int weight;


 public ExternalizableEx() {}
 public ExternalizableEx(String name, int age, int weight) { // 생성자 오버로딩 이름나이 몸무게
  this.name = name; // 각각의 값을 셋팅
  this.age = age;
  this.weight = weight;
 }
 public void writeExternal(ObjectOutput objOutput) // 오버로딩
  throws IOException {
  objOutput.writeObject(name); // 위의 디스에 있는 이름과 나이를 쓰겠다. weight;이건 안씀
  objOutput.writeObject(new Integer(age));
 }
 public void readExternal(ObjectInput objInput) //오버로딩
  throws ClassNotFoundException, IOException {
  name = (String) objInput.readObject();
  age = ((Integer) objInput.readObject()).intValue();
 }
 public String toString() {
  return "name : " + name +
    " , age : " + age +
    " , weight : " + weight;
 }
 public static void main(String[] args) {
  ExternalizableEx ex1 = new ExternalizableEx("홍길동", 33, 70);
  FileOutputStream fos = null;
  ObjectOutputStream oos = null;
  FileInputStream fis = null;
  ObjectInputStream ois = null;
  try {
   fos = new FileOutputStream("c:\\external.ser");  // 여긴씀
   oos = new ObjectOutputStream(fos);
   oos.writeObject(ex1); //ex1이 가지고 있는 것을 가져다 씀
   fis = new FileInputStream("c:\\external.ser"); //여긴 읽는
   ois = new ObjectInputStream(fis);
   ExternalizableEx ex2 = (ExternalizableEx) ois.readObject();
   System.out.println("원본 객체 : " + ex1); //결과값이 읽어올때는 웨이트 값도 다 들어가있는것을 확인할수 있다. / 기본적으로 투스트링이 가지고 있는 것을 찾아서 출력을 하나. 만들어진값이 없으면 기본값으로.
   System.out.println("복원된 객체 : " + ex2); // 결과값이 화일을 썼다가 읽어드리는 경우에는 웨이트 값을 주지 않기 떄문에 0값으로 나오는것을 알수있다.
  } catch (IOException ioe) {
   ioe.printStackTrace();
  } catch (ClassNotFoundException cnfe) {
   cnfe.printStackTrace();
  } finally {
   try {
    if (fis != null) fis.close();
    if (ois != null) ois.close();
    if (fos != null) fos.close();
    if (oos != null) oos.close();
   } catch (IOException ioe) {
    ioe.printStackTrace();
   }
  }
 }
}


--------------------------------
--------------------------------

// 아래 예제는 파일인풋으로 써야되니까. 쓰고 맨마지막에 통째로 오브젝트인풋 아웃을 해서 통째로 작업.

[ObjectInOutputStreamEx.java]
import java.io.*;
public class ObjectInOutputStreamEx {
 public static void main(String[] args) {
  ObjectInputStream ois = null;
  ObjectOutputStream oos = null;
  FileInputStream fis = null;
  FileOutputStream fos = null; //선언
  try {
   fos = new FileOutputStream("c:\\object.ser"); //
   oos = new ObjectOutputStream(fos);
   oos.writeObject(new Customer("성영한")); // 1.writeObject  통빼로 쓰고 이두부분만 특이/// Customer 커스터머라는 것을 사용
   fis = new FileInputStream("c:\\object.ser");
   ois = new ObjectInputStream(fis);
   Customer m = (Customer) ois.readObject(); // 2.readObject() 통째로 보낸다.(스트링 인트 값 따로 하는것이 아니라 파일 하나를 통째로)
   System.out.println(m);
  } catch (IOException ioe) {
   ioe.printStackTrace();
  } catch (ClassNotFoundException cnfe) {
   cnfe.printStackTrace();
  } finally {
   try {
    if (fis != null) fis.close();
    if (ois != null) ois.close();
    if (fos != null) fos.close();
    if (oos != null) oos.close();
   } catch (IOException ioe) {
    ioe.printStackTrace();
   }
  }
 }
}
--------------------------------
--------------------------------
//스트림 토크 나이저를 이용하면 숫자, 문자, 이도저도 아닌것들을 구분가능

[StreamTokenizerEx.java]
import java.io.*;
public class StreamTokenizerEx {
 public static void main(String[] args) {
  BufferedReader br = null;
  StreamTokenizer st = null;
  FileWriter fw = null;
  BufferedWriter bw = null;
  PrintWriter pw = null;
  try {
   fw = new FileWriter("c:\\streamToken.txt"); // :\\streamToken.txt"에서 만들거고
   bw = new BufferedWriter(fw);
   pw = new PrintWriter(bw, true);
   pw.println(10000);
   pw.println("안녕하세요"); // 이텍스트를 파일에 쓰겠다.
   pw.println("nals@lycos.co.kr");
   pw.println("I am a Gentleman");
   pw.println("~`!@#");

   br = new BufferedReader(
     new FileReader("c:\\streamToken.txt"));
   st = new StreamTokenizer(br); // StreamTokenizer를 만듬
   while (st.nextToken() != StreamTokenizer.TT_EOF) { // StreamTokenizer.TT_EOF)구분된 토큰이 있다면  TT_EOF)파일에 끝까지
    switch (st.ttype) {
    case StreamTokenizer.TT_WORD:
     System.out.println("Word => " + st.sval);
     break;
    case StreamTokenizer.TT_NUMBER:
     System.out.println("Number => " +
       (int) st.nval);
     break;
    default:
     System.out.println("No word, No number =>"
       + (char) st.ttype);
     break;
    }
   }
  } catch (IOException ioe) {
   ioe.printStackTrace();
  } finally {
   try {
    if (fw != null) fw.close();
    if (bw != null) bw.close();
    if (pw != null) pw.close();
    if (br != null) br.close();    
   } catch (IOException ioe) {
    ioe.printStackTrace();
   }
  }

 }
}


--------------------------------
--------------------------------
// 읽고 쓰기를 하는 랜덤

[RandomAccessFileEx.java]
import java.io.*;
public class RandomAccessFileEx {
 public static void main(String[] args) {
  RandomAccessFile ra = null;
  try {
   ra = new RandomAccessFile("c:\\random.txt", "rw"); // "rw"읽고 쓰기가 가능한 옵션
   String receive = "hello";
   ra.seek(ra.length()); // seek 찾을때 쓰는 메소드 씨크
   ra.write(receive.getBytes()); // (receive.getBytes())라이트로 이내용을 쓰겠다.
   byte[] buf = new byte[(int) ra.length()];
   ra.seek(0);
   ra.read(buf);
   System.out.print("처음 읽은 내용 : ");
   System.out.println(new String(buf));
   ra.seek(0); // 씨크를 다시 맨앞으로 돌려서 다시 읽게 만듬 , 그럼 헬로우를 다시 읽은것을 확인할수 있음.
   ra.read(buf);
   System.out.print("다시 읽은 내용 : ");
   System.out.println(new String(buf));
  } catch (IOException ioe) {
   ioe.printStackTrace();
  } finally {
   try {
    if (ra != null) ra.close();
   } catch (IOException ioe) {
    ioe.printStackTrace();
   }
  }
 }
}


//스트링 토큰 나이저나 위의 랜덤은 꼭안해도 상관없다.
//최소한 바이트 스트림정도를 기억해두어야한다.
--------------------------------
--------------------------------
//아래와 같은 예제는 자주 갖다 쓰니 알아두는 것이 좋다.

public class Customer implements java.io.Serializable{
 private String name;
 public Customer(String name){
  this.name = name;
}
 public void setName(String name){
  this.name = name;
}
 public String getName(){
  return name;
}
 public String toString(){
  return "당신의 이름 : " +name;
}
}
 

 

import java.io.*;

public class ObjectEx1 {
 public static void main(String[] ar){
  FileOutputStream fos;
  ObjectOutputStream oos;
  FileInputStream fis;
  ObjectInputStream ois;
  File f = new File("aaa.txt");
  try{
   fos = new FileOutputStream(f);
   oos = new ObjectOutputStream(fos);
   Customer cs = new Customer("김용현");
   oos.writeObject(cs);
   
   fis = new FileInputStream("aaa.txt");
   ois = new ObjectInputStream(fis);
   
   Customer obj = (Customer)ois.readObject();
   System.out.println(obj);
   obj.toString();
  }catch(Exception e){}
 }
}


--------------------------------
--------------------------------


--------------------------------
--------------------------------


--------------------------------
--------------------------------


--------------------------------
--------------------------------

TCP/IP( Model에 대해서 배운다.
TCP와 UDP에 대해 배운다.
InetAddress,URL,URLConnection class에 대해 배운다.
Socket(소켓 : 벽에 붙어있는 플로그를 생각. 두사람을 연결한다? 플러그를 꼽는다.)과 ServerSocket class의 흐름과 coding 방법에 대해 배운다.
Unicasting과 multicasting(멀티 테스킹 : 데이터를 주고받으면서)의 개념과 각각의 coding 방법에 대해 배운다.
Protocol 개념과 설계 방법과 이를 이용한 Login 인증 Protocol을 만들어 본다.

 

Network(컴퓨터에 연결되어있는건 모두 네트웍)
 Network란 다른 장치로 Data를 이동시킬 수 있는 Computer들과 주변 장치들의 집합이다.
 Network의 연결된 모든 장치들을 Node라고 한다.
 다른 Node에게 하나 이상의 Service를 해주는 Node를 Host(지금은 서버라고 부른다.)라 부른다.
 하나의 Computer에서 다른 Computer로 Data를 이동시킬 때 복잡한 계층을 통해 전송되는데, 이런 복잡한 Layer의 대표적인 Model이 OSI7 layer Model이다.
 OSI 계층 Model은 모두 7계층으로 이루어졌다.
 Data 통신을 이해하는데 OSI7 Layer Model은 상당한 역할을 하지만, Internet 기반의 표준 Model로 사용하는 TCP/IP 계층 Model을 주로 사용하고 있다.
 Java에서 이야기하는 Network Programming은 TCP/IP Model을 사용하고 있다.

 

Internet Address(IP Address) 아이피 주소는 우리들의 집주소와 똑같다.
 모든 Host는 Internet Address(Host 또는 IP Address)라 불리는 유일한 32bit(122.122.xxx.xx.xx 이런거)  숫자로 구성된 Address체계를 이용하여 서로를 구분할 수 있다.
 IP Address는 32bit 숫자를 한번에 모두를 표현하는 것이 힘들기 때문에, 8 bit씩 끊어서 표현하고, 각 자리는 1byte로 0~255 까지의 범위를 갖게 된다.
 32bit의 Address 체계를 IP Version 4(IPv4) Address라고 한다.
 오늘날 IPv4는 포화 상태이고, 이를 극복하고자 나온 것이 IP Version 6(IPv6)이다.
 IPv6는 128 bit의 Address 체계를 관리하고 있으며, 16bit씩 8부분으로 나누어 16진수 표시한다.
  FECD:BA98:7654:3210:FECD:BA98:7652:3210
 각 Host는 Domain 이름을 Computer가 사용하는 Address(IP Address)로 바꾸어 주어야 한다. 이렇게 IP Address를 Domain 이름으로 바꾸어 주는 System을 DNS(Domain Name System)이라고 한다.

 

Port와 Protocol(포트는 물리적인 포트와 논리적인 포트로 구분된다.)  Protocol 프로토콜은 약속.
 Port는 크게 두 가지로 구분된다.
 Computer의 주변장치를 접속하기 위한 ‘물리적인 Port’와 Program에서 사용되는 접속 장소인 ‘논리적인 Port’가 있다.
 이 장에서 말하는 Port는 ‘논리적인 Port’를 말한다.
 Port번호는 Internet번호 할당 허가 위원회(IANA)에 의해 예약된 Port번호를 가진다.
 이런 Port번호를 ‘잘 알려진 Port들’라고 부른다.
 예약된 Port번의 대표적인 예로는 80(HTTP), 21(FTP), 22(SSH), 23(TELNET)등이 있다.
 Port번호는 0~65535까지 이며, 0~1023까지는 System에 의해 예약된 Port번호이기 때문에 될 수 있는 한 사용하지 않는 것이 바람직하다.

 

Port와 Protocol
 Protocol은 Client와 Server간의 통신 규약이다.
 통신규약이란 상호 간의 접속이나 절단방식, 통신방식, 주고받을 Data의 형식, 오류검출 방식, 코드변환방식, 전송속도 등에 대하여 정의하는 것을 말한다.
 대표적인 Internet 표준 Protocol에는 TCP와 UDP가 있다.
 

 TCP와 UDP
  TCP/IP 계층 Model은 4계층의 구조를 가지고 있다.
  Application, Transfer, Network , Data Link 계층이 있다. (어블리케이션 전송 네트웍..)
  이 중 Transfer계층에서 사용하는 Protocol에는 TCP와 UDP가 있다.

 


TCP(신뢰할수 있는) 그러나 이건 보내기도 하고  다 확인 까지 하기 떄문에 전송속도가 느리다.
 TCP(Transmission Control Protocol)는 신뢰할 수 있는 Protocol로서 , Data를 상대 측까지 제대로 전달되었는지 확인 Message를 주고 받음으로써 Data의 송수신 상태를 점검한다.


UDP(신뢰할수 없는. 보내기만 하는) 편지는 보내놓고 받든지 말든지 상관없는다. 그래서 전송속도가 빠르다.
 UDP(User Datagram Protocol)은 신뢰할 수 없는 Protocol로서, Data를 보내기만 하고 확인 Message를 주고 받지 않기 때문에 제대로 전달했는지 확인하지 않는다.
 TCP ? 전화, UDP - 편지

위의 둘중에 어떤것으로 할지는 프로그래머가 정할일 TCP UDP

 

InetAddress class
 InetAddress class는 IP Address를 표현한 class이다.
 Java에서는 모든 IP Address를 InetAddress class를 사용한다.

 

InetAddress class의 Constructor
 InetAddress class의 Constructor는 하나만 존재하지만, 특이하게 기본 Constructor의 Access Modifier가 default이기 때문에 new 연산자 Object를 생성할 수 없다.
 따라서 InetAddress class는 Object를 생성해 줄 수 있는 5개의 static method를 제공하고 있다.


getAllByName(String host)

getByAddress(byte[ ] addr)


getByAddress(String host, byte[ ] addr)

getByName(String host)

getLocalHost

// 위의 메서드를 통해 아이피 객체 생성 가능

--------------------------------
--------------------------------
//InetAddress iaddr 아이넷 어드레스 이 클래스를 활용해서 아이피주소를 가지고올수가 있다.
//호스트 이름과 아이피 주소들을 가져온다. 맨위에꺼는 내꺼 가져온거
[InetAddressEx.java]
import java.net.*;
public class InetAddressEx {
 public static void main(String[] args)
 throws UnknownHostException {
  InetAddress iaddr = // InetAddress iaddr
   InetAddress.getLocalHost();
  System.out.printf("호스트 이름 : %s %n" ,
    iaddr.getHostName());
  System.out.printf("호스트 IP 주소 : %s %n" ,
    iaddr.getHostAddress());  //컴퓨터 이름과 아이피 주소 부분을 꺼내와서 출력한다.

  iaddr = InetAddress.getByName("java.sun.com");
  System.out.printf("호스트 이름 : %s %n" , 
    iaddr.getHostName());
  System.out.printf("호스트 IP 주소 : %s %n" ,
    iaddr.getHostAddress());
  InetAddress sw[] =

   InetAddress.getAllByName("www.daum.net"); //
  for (InetAddress temp_sw : sw) {
   System.out.printf("호스트 이름 : %s , " , 
     temp_sw.getHostName());
   System.out.printf("호스트 IP 주소 : %s %n" ,
     temp_sw.getHostAddress());
  }
 }
}

 

/////////////////////

 


//주소랑 이름 따오는거 아이넷어드레스
import java.net.*;
public class InetEx1 {
 public static void main(String[] ar){
  InetAddress ia1 = null;
  InetAddress ia2 = null;
  InetAddress[] ia3 = null;
  try{
   ia1 = InetAddress.getLocalHost();
   ia2 = InetAddress.getByName("www.naverㄴㅇㄹㄴㅇㄹ.com"); //겟바이 네임은 하나만 아이피주소
   ia3 = InetAddress.getAllByName("www.naver.com"); // 올바이 네임은 배열로 뽑아줘야한다. 아이피 주소 전부나옴
   System.out.println(ia1);
   System.out.println(ia2);
   for(int i = 0; i < ia3.length; ++i){
    System.out.println(ia3[i]);
   }
   
   //System.out.println(ia3);
   
  }catch(UnknownHostException e){ //트라이 캐치문 안에 어떤거 하나라도 걸리면 쉬팔.뜸
   System.out.println("쉬팔");
  }
 }
}


--------------------------------
--------------------------------
URL class
 URL(Uniform Resource Locator)이란 Internet에서 접근 가능한 Resource의 Address를 표현할 수 있는 형식을 말한다.
(프로토콜 호스트 포트 패스 콰이라 레퍼런스)


URL class의 Constructor
 URL class는 URL을 추상화 하여 만든 class다.
 URL class는 final class로 되어 있기 때문에 상속하여 사용할 수 없다.
 모든 Constructor는 MalformedURLException 예외를 발생하기 때문에 반드시 예외처리를 해야 한다.


URLConnection class (유알엘 커넥션은 위의 유알엘 클래스와 거의 같은 클래스이나 원격에 있는 컴퓨터의 정보를 더 많이 가지고 올수가있다.)
 URLConnection class는 원격 Resource에 접근하는 데 필요한 정보를 가지고 있다.
 필요한 정보란 원격 Server의 Header 정보, 해당 Resource의 길이와 타입 정보, 언어 등을 얻어 올 수 있다.
 URL class는 원격 Server Resource의 결과만을 가져 오지만, URLConnection class는 원격 Server Resource의 결과와 원격 Server의 Header 정보를 가져 올 수 있다.

 

URLConnection class의 Constructor
 URLConnection class는 Abstract class이기 때문에 단독적으로 Object를 생성할 수 없다.
 URL class의 Object를 생성해서 URL class의 openConnection() method를 이용해서 Object를 생성해야 한다.
 URLConnection Object가 생성 되었다면 URLConnection class의 connect() method를 호출해야 Object가 완성된다.

URL url = new URL(“http://java.sun.com”);
URLConnection urlCon = url.openConnection();
urlCon.connect();

 

 

 

--------------------------------
--------------------------------

[URLEx.java]
import java.net.*;
import java.io.*;
public class URLEx {
 public static void main(String[] args)
 throws MalformedURLException, IOException {
  URL url = new URL("http", "java.sun.com", 8800, //프로토콜 패스  문서 등의 매개변수를 넣음 완전히 유알엘을 만들기위해
    "index.jsp?name=syh1011#content"); // 이줄을 하나하나 다 분해해서 다시 조합. 위의 예제가 더 쉬움 일단...
  String protocol = url.getProtocol();
  String host = url.getHost();
  int port = url.getPort();
  int defaultPort = url.getDefaultPort(); // DefaultPort디폴트 폴트

  String path = url.getPath(); //겟패스를 뽑으면
  String query = url.getQuery(); //쿼리를 뽑으면
  String ref = url.getRef();
  String _url = url.toExternalForm();
  String mixUrl = null;
  if (port == -1) { // port == -1) 포트가 -1이라는건 포트를 주지 않은것
   mixUrl = protocol + "//" + host + path +
     "?" + query + "#" + ref;
  } else {
   mixUrl = protocol + "//" + host + ":" +
   port + path + "?" + query + "#" + ref;
  }
  if (port == -1)
   port = url.getDefaultPort();
  System.out.printf("프로토콜 : %s %n", protocol); // 각각을 뽑아 출력시켜라.
  System.out.printf("호스트 : %s %n", host);
  System.out.printf("포트 : %d %n", port);
  System.out.printf("패스 : %s %n", path);
  System.out.printf("쿼리 : %s %n", query);
  System.out.printf("ref : %s %n", ref);
  System.out.printf("mixURL : %s %n", mixUrl);
  System.out.printf("URL : %s %n", _url);

  url = new URL("http://java.sun.com"); // "http://java.sun.com"); 이거를 유알엘 객체로 선언
  InputStream input = url.openStream(); //url.openStream() 유알엘 클래스의 오픈 스트림의 메소드는 애를 읽어드려서 객체를 생성해라. openStream() 오픈스트램 메소드를 리턴해준다.
  int readByte;
  System.out.println("=== 문서의 내용 ===");
  while (((readByte = input.read()) != -1)) {
   System.out.print((char) readByte);
  }
  input.close();

 }
}
--------------------------------
--------------------------------

//헤더라는 부분의 정보를 끄집어내서 출력한것 을 확인 할수 있다.
// 다 읽어와서 출력해주는것을 확인할수 있다.

[URLConnectionEx.java]
import java.net.*;
import java.io.*;
import java.util.*;
class URLConnectionEx{
 public static void main(String[] args) throws Exception{

  URL url = new URL("http://java.sun.com/j2se/1.5.0/docs/api/overview-summary.html"); //유알엘 객체를 생성한다.
  URLConnection urlCon = url.openConnection(); // openConnection()를 리턴해주는 값으로  urlCon 생성
  urlCon.connect(); //  URLConnection 사용할떄 하나의묶음 여기까지
  
        Map<String , List<String>> map = urlCon.getHeaderFields(); // HeaderFields 헤더필드. 에 저장되는 값들이 웹에 저장.
        Set<String> s = map.keySet();
        Iterator<String> iterator = s.iterator(); // iterator이터웨이터로 반복을 해주고
        while(iterator.hasNext()){
            String name = iterator.next();
            System.out.print(name + " : ");
            List<String> value = map.get(name);
            for(String _temp : value)
                System.out.println(_temp);
        }
  int len = urlCon.getContentLength();
  System.out.println("문서의 길이  : "+len+" 바이트");
  if(len>0){
   InputStream input = urlCon.getInputStream();
            System.out.println("=== 문서의 내용 ===");
            int readByte;
            while(((readByte = input.read()) != -1) && (--len>0)){
    System.out.print((char)readByte);
   }
   input.close();
  }else{
   System.out.println("내용이 없음");
  }  
 }
}

//InetAddress,URL,URLConnection class에 대해 배운다. 의 사용방법을 알아야 소켓을 사용해서 작업하는것을 진행할수 있다.

//아이오가 베이스가 되고 네트웍 쓰레스 스윙 기본적인 이벤트 (그동안 기본적으로 그동안 배운것을 다 넣고 가야 작업하기 편하다.)(뒤에껄 공부하면서 모르는 부분을 찾아가면서 채워나가야한다.)
--------------------------------
--------------------------------
import java.net.*;
class  InetAddressEx{
 public static void main(String[] args) throws UnknownHostException {
  InetAddress addr1 = InetAddress.getByName("naver.com");
  InetAddress addr2 = InetAddress.getByName("59.5.12.241");
  InetAddress addr3 = InetAddress.getLocalHost();
  System.out.println("=====================================");
  System.out.println("addr1 = "+addr1.getHostAddress());
  System.out.println("addr2 = "+addr2.getHostName());
  System.out.println("로컬주소 = "+addr3.getHostAddress());
  System.out.println("로컬이름 = "+addr3.getHostName());
 }
}


--------------------------------
--------------------------------
//위의 ㅡ예제는 다이렉트 입력. 이건 직접
import java.net.*;
import java.io.*;
class  InetAddress2{
 public static void main(String[] args)throws Exception {
  String url = null;
  BufferedReader reader =
   new BufferedReader(new InputStreamReader(System.in));
  System.out.print("웹 사이트 주소 입력 ==> ");
  url = reader.readLine();
  InetAddress addr = InetAddress.getByName(url);
  System.out.println("===================================");
  System.out.println(url+"의 IP 번호 = " + addr.getHostAddress());
 }
}


--------------------------------
--------------------------------
//배열이 들어갔다는것만...

import java.net.*;
import java.io.*;
class  InetAddress3{
 public static void main(String[] args)throws Exception {
  String url = null;
  BufferedReader reader =
   new BufferedReader(new InputStreamReader(System.in));
  System.out.print("웹 사이트 주소 입력 ==> ");
  url = reader.readLine();
  InetAddress [] addr = InetAddress.getAllByName(url);
  System.out.println("==================================");
  System.out.println(url+"는 "+addr.length+"개의 IP주소를 갖고 있습니다.");
  for(int i = 0; i < addr.length; i++){
   System.out.println((i+1)+"번 IP 번호 = " + addr[i].getHostAddress());
  }}}

--------------------------------
--------------------------------

import java.net.*;
import java.io.*;
class  UrlEx1{
 public static void main(String[] args) throws Exception{
  String urlstr = null;
  BufferedReader reader =
   new BufferedReader(new InputStreamReader(System.in));
  System.out.print("URL 페이지 입력==>");
  urlstr = reader.readLine().trim(); // trim()쓰면 공백 제거
  URL url = new URL(urlstr);
  System.out.println("프로토콜 : "+url.getProtocol());
  System.out.println("포트번호 : "+url.getPort());
  System.out.println("호스트 : "+url.getHost());
  System.out.println("URL 내용 : "+url.getContent());
  System.out.println("파일경로 : "+url.getFile());
  System.out.println("URL 전체 : "+url.toExternalForm());
 }
}

--------------------------------
--------------------------------


--------------------------------
--------------------------------

댓글