100일 챌린지/빅데이터기반 인공지능 융합 서비스 개발자

Day 19 - Java 네트워크(java.net)

ksyke 2024. 8. 19. 13:58

목차

    InetAddress

    java.net.InetAddress inet01 = null;
    
    String host = "google.com";
    
    try {
        inet01 = InetAddress.getByName(host);
        System.out.println(inet01.getHostName()); // google.com
        System.out.println(inet01.getHostAddress()); // 142.250.206.206
        System.out.println(inet01.getCanonicalHostName()); // kix07s07-in-f14.1e100.net - 실질 서버 
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    java.net.InetAddress[] inets = null;
    
    String host = "daum.net";
    
    try {
        inets = InetAddress.getAllByName(host);
        for(int i = 0; i < inets.length; i++) {
            InetAddress inet = inets[i];
        System.out.println(inet.getHostName()); 
        System.out.println(inet.getHostAddress()); 
        System.out.println(inet.getCanonicalHostName()); 
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    // 0.0.0.0 ~ 255.255.255.255 (4byte의 주소 체계)
    byte[] addr = new byte[] {(byte)172, (byte)217, (byte)161, (byte)238};
    inet01 = InetAddress.getByAddress(addr);
    System.out.println(inet01.getHostName()); 
    System.out.println(inet01.getHostAddress()); 
    java.net.URL url = null;
    try {
        String path = "https://getbootstrap.com/docs/3.4/components/#navbar";
        url = new URL(path);
        System.out.println(url.getProtocol()); // https
        System.out.println(url.getHost()); // getbootstrap.com
        System.out.println(url.getPort()); // -1
        System.out.println(url.getDefaultPort()); // 443
        System.out.println(url.getFile()); // /docs/3.4/components/
        System.out.println(url.getPath()); // /docs/3.4/components/
        System.out.println(url.getQuery()); // null
        System.out.println(url.getAuthority()); // getbootstrap.com
        System.out.println(url.getRef()); // navbar
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    java.net.URLConnection conn = null;
    java.net.URL url= null;
    
    java.io.InputStream is = null;
    java.io.InputStreamReader isr = null;
    
    String spec = "https://google.com";
    
    try {
        url = new URL(spec);
        conn = url.openConnection(); // 서버에 접속
        is = conn.getInputStream();
        isr = new InputStreamReader(is);
    
        while(true) {
            int su = isr.read();
            if(su == -1) break;
            System.out.print((char)su);
        }
    
        isr.close();
        is.close();
    
    } catch (IOException e) {
        e.printStackTrace();
    }        

    web scrapping 하기

    java.net.URLConnection conn = null;
    java.net.URL url= null;
    
    java.io.InputStream is = null;
    java.io.InputStreamReader isr = null;
    
    String spec = "https://google.com";
    File f = new File("google.html");
    
    OutputStream os = null;
    
    try {
        os = new FileOutputStream(f);
    
        url = new URL(spec);
        conn = url.openConnection(); // 서버에 접속
        is = conn.getInputStream();
    
        while(true) {
            int su = is.read();
            if(su == -1) break;
            os.write(su);
        }
    
        os.close();
        is.close();
    
    } catch (IOException e) {
        e.printStackTrace();
    }
    java.net.URLConnection conn = null;
    java.net.URL url= null;
    
    InputStream is = null;
    InputStreamReader isr = null;
    
    String spec = "https://daum.net";
    
    OutputStream os = null;
    try {
        url = new URL(spec);
        conn = url.openConnection(); // 서버에 접속
        is = conn.getInputStream();
        isr = new InputStreamReader(is, "UTF-8");
                String msg = "";
    
        while(true) {
            int su = isr.read();
            if(su == -1) break;
            System.out.print((char)su);
            msg += ((char)su);
        }
    
        System.out.println("완료");
    
        int beginIdx = msg.indexOf("인덱스 문장");
        int endIdx = msg.indexOf("<!-- 인덱스 문장 -->");
        msg = msg.substring(beginIdx, endIdx);
        msg = msg.replaceAll("\t", "");
        System.out.println(msg);
    
        isr.close();
        is.close();
    
    } catch (IOException e) {
        e.printStackTrace();
    }

    다운로드 프로그램 만들기

    java.net.URLConnection conn = null;
    java.net.URL url= null;
    
    InputStream is = null;
    InputStreamReader isr = null;
    
    String spec = "https://www.7-zip.org/a/7z2408-x64.exe";
    File f = new File("7z.exe");
    
    OutputStream os = null;
    
    try {
        os = new FileOutputStream(f);
    
        url = new URL(spec);
        conn = url.openConnection(); // 서버에 접속
        is = conn.getInputStream();
    
        while(true) {
            int su = is.read();
            if(su == -1) break;
            os.write(su);
        }
        System.out.println("다운로드 완료");
        os.close();
        is.close();
    
    } catch (IOException e) {
        e.printStackTrace();
    }
    Buffer를 사용한 다운로드 속도 올리기
    java.net.URLConnection conn = null;
    java.net.URL url= null;
    
    InputStream is = null;
    InputStreamReader isr = null;
    
    String spec = "https://www.7-zip.org/a/7z2408-x64.exe";
    File f = new File("7z_1.exe");
    
    OutputStream os = null;
    
    BufferedInputStream    bis = null;
    BufferedOutputStream    bos = null;
    try {
        os = new FileOutputStream(f);
        url = new URL(spec);
        conn = url.openConnection(); // 서버에 접속
        is = conn.getInputStream();
        bis = new BufferedInputStream(is);
        bos = new BufferedOutputStream(os);
        byte[] buf = new byte[512];
    
        while(true) {
            int su = is.read(buf);
            if(su == -1) break;
            os.write(buf, 0, su);
        }
    
        System.out.println("다운로드 완료");
        bos.close();
        bis.close();
        os.close();
        is.close();
    
    } catch (IOException e) {
        e.printStackTrace();
    }

    host

    • DNS에 ip 주소를 물어보기 전 호스트 파일이 더 우선순위에 있다.
    • 우선순위: hosts -> node Root -> DNS

    C:\Windows\System32\drivers\etc



    채팅 프로그램 만들기

    • HW : 1 ~ 2 계층
    • OS(SW) : 3 ~ 4 계층
    • SW : 5 ~ 7 계층

    TCP / UDP

    • tcp: 순서를 보장 (대체로 사용되는 방식)
    • udp: 순서를 보장하지 않음. 피켓이 loss될 수도 있음 (예: 방송 송출)

    port

    • 물리적인 포트와 개념적인 포트가 존재한다.
    • 송수신하는 데이터의 유형을 관리
    • 관문 역할을 한다.(예: 방화벽)

    서버와 클라이언트 만들기

    기본

    Server
    public class Server{
    
        public static void main(String[] args) {
            int port = 5000;
            ServerSocket serv = null;
            Socket sock = null;
    
            InputStream is = null;
            OutputStream os = null;
    
            try {
                serv = new ServerSocket(port);
                System.out.println("waiting to connect...");
    
                sock = serv.accept();
                InetAddress addr = sock.getInetAddress();
                is = sock.getInputStream();
                os = sock.getOutputStream();
                byte[] buf = new byte[10];
                is.read(buf);
                System.out.println("connecting to... " + addr.getHostAddress());
                System.out.println(new String(buf));
                os.write("welcome".getBytes());
                os.write(255);
    
                while(true) {
                    int su = is.read();
                    if(su == -1) break;
                    System.out.print((char)su);
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                    try {
                        if(os != null) os.close();
                        if(is != null) is.close();
                        if(sock != null) sock.close();
                        if(serv != null) serv.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        }
    }
    Client
    public class Client {
    
        public static void main(String[] args) {
    
            int port = 5000;
            Socket sock = null;
    
            OutputStream os = null;
            InputStream is = null;
    
            byte[] ip = new byte[] {(byte)192, (byte)168, (byte)219, (byte)125};
    
            try {
    
                InetAddress addr = InetAddress.getByAddress(ip);
                sock = new Socket(addr, port);
                os = sock.getOutputStream();
                is = sock.getInputStream();
                os.write("hello java".getBytes());
    
                while(true) {
                    int su = is.read();
                    if(su == 255) break;
                    System.out.print((char)su);
                }
                os.write("me too".getBytes());
    
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(is != null) is.close();
                    if(os != null) os.close();
                    if(sock != null) sock.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
        }
    }

    하나의 클라이언트와 통신하는 서버 (InputStreamReader)

    Server
    public class Server {
    
        public static void main(String[] args) {
            int port = 5000;
            ServerSocket serv = null;
    
            InputStream is = null;
            InputStreamReader isr = null;
            BufferedReader br = null;
    
            try {
                serv = new ServerSocket(port);
                while(true) {
                    Socket sock = serv.accept();
                    is = sock.getInputStream();
                    isr = new InputStreamReader(is);
                    br = new BufferedReader(isr);
                    while(true) {
                        String msg = br.readLine();
    
                        System.out.println(sock.getInetAddress().getHostAddress() + " >> " + msg);
                    }
    
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(is != null) is.close();
                    if(serv != null) serv.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
        }
    }
    Client
    public class Client {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    
            int port = 5000;
            Socket sock = null;
    
            OutputStream os = null;
            PrintStream ps = null;
    
            try {
    
                sock = new Socket(InetAddress.getByAddress(new byte[] {(byte)192, (byte)168, 54, 90}), port);
                os = sock.getOutputStream();
                ps = new PrintStream(os);
    
                while(true) {
                    System.out.print("client >> ");
                    String msg = sc.nextLine();
    //                ps.println(msg);
                    ps.write(msg.getBytes());
                    ps.write("\n".getBytes());
                    ps.flush();
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(ps != null) ps.close();
                    if(os != null) os.close();
                    if(sock != null) sock.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
        }
    }

    여러 클라이언트와 통신하는 서버

    Server
    public class Server extends Thread{
        Socket sock;
    
        public Server(Socket sock) {
            this.sock = sock;
        }
    
        @Override
        public void run() {
            String ip = sock.getInetAddress().getHostAddress();
            try(
                    InputStream is = sock.getInputStream();
                    OutputStream os = sock.getOutputStream();
                    InputStreamReader isr = new InputStreamReader(is);
                    BufferedReader br = new BufferedReader(isr);
                    PrintStream ps = new PrintStream(os)
                    ){
                while(true) {
                    String msg = br.readLine();
                    ps.println(ip + " >> " + msg);
                    ps.flush();
                }
    
            } catch (IOException e) {
                        e.printStackTrace();
                    }
        }
    
        public static void main(String[] args) {
            int port = 5000;
    
            ServerSocket serv = null;
    
            try {
    
                serv = new ServerSocket(port);
    
                while(true) {
                    Socket sock = serv.accept();
                    Server thr = new Server(sock);
                    thr.start();
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(serv != null) serv.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
        }
    }
    Client
    public class Client {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    
            int port = 5000;
            Socket sock = null;
    
            OutputStream os = null;
            InputStream is = null;
            PrintStream ps = null;
            InputStreamReader isr = null;
            BufferedReader br = null;
    
            try {
    
                sock = new Socket(InetAddress.getByAddress(new byte[] {(byte)192, (byte)168, 54, 90}), port);
                os = sock.getOutputStream();
                ps = new PrintStream(os);
                is = sock.getInputStream();
                isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
    
                while(true) {
                    System.out.print("client >> ");
                    String msg = sc.nextLine();
                    ps.println(msg);
                    ps.flush();
                    String result = br.readLine();
                    System.out.println(result);
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(ps != null) ps.close();
                    if(os != null) os.close();
                    if(sock != null) sock.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
        }
    }

    UI 를 사용한 채팅 프로그램 만들기, 클라이언트가 나갈때 에러 없애기

    Server
    public class Server implements Runnable{
        Socket sock;
        static ArrayList<Socket> list;
    
        public Server(Socket sock) {
            this.sock = sock;
        }
    
        public void sendAll(String msg) {
    
            for(int i = 0; i < list.size(); i++) {
                Socket sock = list.get(i);
                try {
                    OutputStream os = sock.getOutputStream();
                    PrintStream ps = new PrintStream(os);
                    ps.println(msg);
                    ps.flush();
                } catch (IOException e) {
                    list.remove(sock);
                }
            }
        }
    
        @Override
        public void run() {
    
            try {
                InputStream is = sock.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                while(true) {
                    String msg = br.readLine();
                    sendAll(sock.getInetAddress().getHostAddress() + ">>" + msg);
                    }
            } catch (IOException e) {
                list.remove(sock);
            }
        }
    
        public static void main(String[] args) {
             list = new ArrayList<>();
    
            try(
                    ServerSocket serv = new ServerSocket(6000);
                    ) {
                while(true) {
                    Socket sock = serv.accept();
                    Server me = new Server(sock);
    
                    Thread thr = new Thread(me);
                    thr.start();
                    list.add(sock);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    }

    => 클라이언트 인덱스를 ip주소로 받으면 클라이언트가 나가도 index가 바뀌지 않는다.

    Client
    public class Client extends Frame implements ActionListener{
        TextField tf;
        static PrintStream ps;
    
        public Client() {
            tf = new TextField();
            tf.addActionListener(this);
            add(tf);
            setBounds(600, 300, 300, 100);
            setVisible(true);
        }
    
        public static void main(String[] args) {
            Client me = new Client();
    
            int port = 6000;
    
            try(
                    Socket sock = new Socket("127.0.0.1", port);
                    InputStream is = sock.getInputStream();
                    OutputStream os = sock.getOutputStream();
                    InputStreamReader isr = new InputStreamReader(is);
                    BufferedReader br = new BufferedReader(isr);
                    ) {
                ps = new PrintStream(os);
                while(true) {
                    String msg = br.readLine();
                    System.out.println(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            String msg = tf.getText();
            ps.println(msg);
            ps.flush();
            tf.setText("");
        }
    }