Java/Java

JAVA 네트워크

code2772 2022. 10. 20. 16:02
728x90
반응형
1. 네트워크(Network)
- Net + work 합성어
- 컴퓨터들이 통신 기술을 이용하여 그물망처럼 연결된 통신 이용형태

인터넷(Internet)
- 컴퓨터로 연결하여 TCP/IP 프로토콜을 이용하여 정보를 주고받는 네트워크

✔ IP(Internet Protocol)
- 인터텟 연결되어 있는 모든 장치를 식별할 수 있도록 장비에게 부여되는 고유 주소

✔ IPv4
- 8bit씩 4자리
- 하나의 스텟마다 0 ~ 255 (0 ~ 42억9천)
    예) 211.100.85.100
- 향후 IPv6, 32bit

내 아입피 확인
- 네이버 "내 ip"로 검색 -> 123.142.55.115
- cmd -> ipconfig -> 192.168.12.12

도메인 -> IP, IP -> 도메인
- cmd -> nslookup

✔ 포트(port)
- 컴퓨터나 통신장비에서 다른 장치에 물리적으로 접속되는 특정한 통로

InetAddress 클래스
- IP 주소 관련 클래스(실제 아이피를 가저올 수 있음)
- getHostName() : 도메인을 리턴
- getHostAddress() : IP주소를 리턴

USRL 클래스
- URL(인터넷 창에 들어가는 부분) 주소 관련 클래스 - 내가 찾는것이 무엇인지/보고자하는 것 등을 전부 확인
- getProtocol()// 프로토콜을 출력 https:와 같은것
- getHost() // 호스트(도메인)
- getPort() // 기본값 -1(80)
- getPath(); // https 같은것(도메인) 뒤에 나오는 리소스
- getQuery(); // 값 (응답) - 내가 보내는(검색) 값을 전달해준다.

URLConnection 클래스
- URL 클래스 보다 추가된 기능, 연결에 대한 정보를 리턴

버퍼(buffer)
- 입출력을 수행하는데 있어 속도차이를 극복하기 위해 사용하는 임시 저장 공간
- 프로그래밍이나 운영체제에서 cpu와 보조기억장치 사이에서 사용되는 임시 저장 공간

BufferedReader 클래스
- 데이터(문자)를 버퍼에 담아줌


BufferedInputStream 클래스
- 바이너리를 버퍼에 담아줌 [(음악, 영상, 사진) 과 같은 문자가 아닌]

 

import java.net.InetAddress;
import java.net.UnknownHostException;

public class Network1 {
    public static void main(String[] args) {
        try {
//            InetAddress inetAddress = InetAddress.getByName("www.naver.com");
//              도메인 내임을 겟 네임에 주면 아이피 어드레스를 얻을 수 있다/}
//            System.out.println(inetAddress.getHostName());
//              도메인을 츨력한다. www.naver.com
//            System.out.println(inetAddress.getHostAddress());
//              IP주소 223.130.200.107

            InetAddress[] inetAddress = InetAddress.getAllByName("www.naver.com");
            // 배열로 모든 도메인 네임에 있는 아이피 어드레스를 가저온다
     for(InetAddress iAdd : inetAddress){
         System.out.println(iAdd.getHostAddress());
         // 공개 IP 전부 찍힘 223.130.195.200
                          //223.130.195.95
     }
        } catch (UnknownHostException e) {//강제
            e.printStackTrace();
        }
    }
}

 

import java.net.MalformedURLException;
import java.net.URL;

public class Network2 {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=c4i&oquery=" +
                    "%EB%82%B4+ip&tqi=h09aCsprvxZssLrqXLwssssssB8-375298");

            System.out.println(url.getProtocol());// 프로토콜을 출력 https:와 같은것
            System.out.println(url.getHost()); // 호스트(도메인)
            System.out.println(url.getPort()); // 기본값 -1(80)
            System.out.println(url.getPath()); // https 같은것(도메인) 뒤에 나오는 리소스
            System.out.println(url.getQuery()); // 값 (응답) - 내가 보내는(검색) 값을 전달해준다.

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

 

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Network3 {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.koreaisacademy.com/");
            URLConnection conn = url.openConnection();

            System.out.println(conn);
            //sun.net.www.protocol.https.DelegateHttpsURLConnection:https://www.koreaisacademy.com/
            // 데이터를 보여줌
            System.out.println(conn.getContent());
            //sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@be35cd9
            System.out.println(conn.getDate());// 1666142580000 -> timestamp를 알 수 있다. 접속시간 확인
            System.out.println(conn.getURL());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
// buffer 이를 통해 크롤링은 가능하지만 자바로 하는것은 추천하지는 않는다. 파이썬으로 하는게 편하다 크롤링의 경우
public class Network4 {
    public static void main(String[] args) {
        BufferedReader br =null;

        try {
            URL url = new URL("https://www.koreaisacademy.com/");
           // InputStream isr = new InputStreamReader(url.openStream());
            // br = new BufferedReader(isr); 이렇게 해도 괜찮지만 밑에 방식이 더 편하다.
            br = new BufferedReader(new InputStreamReader(url.openStream()));
            // 버퍼리더 임시저장
            //url.openStream() url을 열어 데이터를 가저온다. 스트림을 통해 가저와야하고 인풋스트림이 있어야한다.
            String data = null;
            while((data = br.readLine()) != null ){//읽을게 있으면
                System.out.println(data);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {// 무조건 들림 파이널리는
            {
                if(br != null){ // 버퍼가 존재한다면 없에라
                    try {
                        br.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

public class Network5 {
    public static void main(String[] args) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        String url = "https://t1.daumcdn.net/daumtop_chanel/op/20200723055344399.png";
        // 이미지 주소 복사

        try {
            URLConnection conn = new URL(url).openConnection();
            // 이미지에 대한 객체를 가저와서 연결할 수 있게
            bis = new BufferedInputStream(conn.getInputStream());
            // 내가 유얼엘에 저장한것을 스트림으로 저장하여 버퍼에 담는다.
            bos = new BufferedOutputStream(new FileOutputStream("./daum.jpg"));
            // 버퍼에서 내보낸다 파일형태로

            int data =0;
            while((data = bis.read()) != -1){ // -1 끝이 날땍까지
                bos.write(data);
            }
            System.out.println("파일 생성완료!");
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(bis != null)
                try{
                    bis.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            if(bos != null)
                try{
                    bis.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
        }


    }
}
반응형

'Java > Java' 카테고리의 다른 글

JAVA 채팅 프로그램  (0) 2022.10.20
JAVA (TCP/IP, 서버 클라이언트)  (0) 2022.10.20
자바 제네릭(Generic)  (0) 2022.10.12
자바 스레드  (0) 2022.10.07
자바 영어단어장  (0) 2022.10.07