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

Day20 - TCP/UDP 통신과 Web Server

ksyke 2024. 8. 20. 12:42

소스코드에서 원하는 데이터 뽑기

public class Ex01 {
    public static void main(String[] args) {

        String msg = "https://www.weather.go.kr/weather/forecast/mid-term-rss3.jsp?stnld=159";
        URL url = null;
        URLConnection conn = null;
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        try {
            url = new URL(msg);
            conn = url.openConnection();
            is = conn.getInputStream();
            isr = new InputStreamReader(is, "UTF-8");
            br = new BufferedReader(isr);
            String result = "";
            while((msg = br.readLine()) != null){
//                System.out.println(msg);
                result += msg + "\n";
            }
//            result = result.substring(result.indexOf("경상남도"));
//            result = result.replaceAll("\t", "");
//            System.out.println(result);
            int begin = result.indexOf("<![CDATA[");
            int end = result.indexOf("]]>");
            result = result.substring(begin, end);
            result = result.replaceAll("<br />", "\n");
            result = result.replaceAll("<[^>]*>", "");
            System.out.println(result);

        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(is != null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

IP / Port에 대해

공용 IP/ 사설 IP

  • 공용 IP
    • 인터넷선으로 바로 들어오는 IP
  • 사설 IP
    • 내부적으로만 사용 가능하다.
    • 공유기로 공유된 IP (외부에서 접근하지 못한다.)
    • IP 주소의 중복이 가능하다.

고정 IP/ 유동 IP

  • 고정 IP
  • 유동 IP
    • 공유기에서 자체적으로 나눠주는 유동적인 IP 주소

Port

  • IP 주소 뒤에 :를 따라오는 번호 (6555까지의 번호가 있다.)
  • 0 ~ 1023 : 예약된 포트번호
  • 1024 ~ 49151 : 등록된 포트
  • 49152 ~ 6555 : 동적 포트
  • 80 : WWW HTTP
  • 443 : TSL.SSL 방식의 HTTP

PC 통신

TCP

Server

public class Server extends Thread{
    static Map<String, PrintStream> map;
    String id;
    InputStream is;

    public Server(String id, InputStream is) {
        this.id = id;
        this.is = is;
    }

    @Override
    public void run() {
        try(
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                ){
            String msg = "";
            while(true) {
                msg = br.readLine();
                Set<String> keys = map.keySet();
                Iterator<String> ite = keys.iterator();
                while(ite.hasNext()) {
                    String key = ite.next();
                    try {
                        PrintStream ps = map.get(key);
                        ps.println(id + " >> " + msg);
                        ps.flush();
                    }catch(Exception e) {
                        map.remove(key);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {

        map = new HashMap<String, PrintStream>();

        try(
                ServerSocket serv = new ServerSocket(6000);
                ){
            while(true) {
                Socket sock = serv.accept();
                OutputStream os = sock.getOutputStream();
                PrintStream ps = new PrintStream(os);
                String id = sock.getInetAddress().getHostAddress();
                PrintStream ps_msg = new PrintStream;
                InputStream is = sock.getInputStream();
                map.put(id, ps);

                Server me = new Server(id, is);
                me.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client

public class Client extends Frame implements ActionListener{
    static TextArea ta;
    TextField tf, id;
    static PrintStream ps;

    public Client() {
        setLayout(new BorderLayout());

        ta = new TextArea();
        add(ta, BorderLayout.CENTER);
        tf = new TextField();
        tf.addActionListener(this);
        add(tf, BorderLayout.SOUTH);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                dispose();
            }
        });
        setBounds(100, 100, 300, 500);
        setVisible(true);
    }

    public static void main(String[] args) {
        Client me = new Client();

        InputStream is = null;
        OutputStream os = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try(                
                Socket sock = new Socket("127.0.0.1", 6000);
                ) {
            is = sock.getInputStream();
            os = sock.getOutputStream();
            ps = new PrintStream(os);
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);

            String msg = null;
            while(true) {
                msg = br.readLine();
                ta.appendText(msg + "\n");
            }

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

    @Override
    public void actionPerformed(ActionEvent e) {
        String msg = tf.getText();
        ps.println(msg);
        ps.flush();
        tf.setText("");
    }
}

UDP

Sender

public class Sender {

    public static void main(String[] args) {
        byte[] ip = new byte[]{(byte)127, 0, 0, 1};
        int port = 6000;

        DatagramSocket sock = null;
        DatagramPacket p = null;

        try {
            InetAddress addr = InetAddress.getByAddress(ip);
            sock = new DatagramSocket();

            String msg = "Hello";
            byte[] buf = msg.getBytes();
            p = new DatagramPacket(buf, buf.length, addr, port);
            sock.send(p);

            msg = "한글";
            buf = msg.getBytes();
            p = new DatagramPacket(buf, buf.length, addr, port);
            sock.send(p);


        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(sock != null) sock.close();
        }
    }
}

Receiver

public class Receiver {

    public static void main(String[] args) {
        byte[] buf = new byte[5]; // UDP는 받는 사이즈가 지정되어있어야 한다. 

        DatagramSocket sock = null;
        DatagramPacket p = null;

        try {
            sock = new DatagramSocket(6000);

            p = new DatagramPacket(buf, buf.length);
            sock.receive(p);
            System.out.println(new String(buf));

            p = new DatagramPacket(buf, buf.length);
            sock.receive(p);
            System.out.println(new String(buf));

        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(sock != null) sock.close();
        }
    }
}

Web Server

  • 80번 포트로 서비스가 되고 있는 IO 서비스

80번 포트의 웹 서버 만들기

try(
        ServerSocket serv =  new ServerSocket(8080);
        ){
    System.out.println("대기");
    serv.accept();
    System.out.println("접속됨");
} catch (IOException e) {
    e.printStackTrace();
}
public class Ex03 extends Thread{
    InputStream is;
    OutputStream os;

    public Ex03(Socket sock) throws IOException {
        is = sock.getInputStream();
        os = sock.getOutputStream();
    }

    @Override
    public void run() {
        try {
//            os.write("Hello".getBytes());
            // http protocol 규격 맞추기 
            os.write("HTTP/1.1 200 OK\n".getBytes());
            os.write("\n".getBytes());
            os.write("Hello\n".getBytes());
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        try(
                ServerSocket serv =  new ServerSocket(8080);
                ){
            while(true) {
                System.out.println("대기");
                new Ex03(serv.accept()).start();
                System.out.println("접속됨");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
curl http://127.0.0.1

혹은

http://localhost:8080/
public class Ex03 extends Thread{
    InputStream is;
    OutputStream os;

    public Ex03(Socket sock) throws IOException {
        is = sock.getInputStream();
        os = sock.getOutputStream();
    }

    @Override
    public void run() {
        try{
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String msg = br.readLine();
            String[] arr = msg.split(" ");

        } catch (IOException e1) {
            e1.printStackTrace();
        }



//        File f = new File("ball1.jpg");
        File f = new File("www/ex01.html");
        try {
            InputStream is = new FileInputStream(f);
//            os.write("Hello".getBytes());
            // http protocol ±Ô°Ý ¸ÂÃß±â 
            os.write("HTTP/1.1 200 OK\n".getBytes());
            // Content-Type: text/html; charset=UTF-8
//            os.write("Content-Type: text/plain; charset=UTF-8\n".getBytes());
//            os.write("Content-Type: image/jpeg; charset=UTF-8\n".getBytes());
            os.write("Content-Type: text/html; charset=UTF-8\n".getBytes());
            os.write("\n".getBytes());
//            os.write("<h1>Hello</h1>".getBytes());
//            os.write("<h2>이것은 테스트 페이지 입니다.</h2>".getBytes());

            while(true) {
                int su = is.read();
                if(su == -1) break;
                os.write(su);
            }
            is.close();
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        try(
                ServerSocket serv =  new ServerSocket(8080);
                ){
            while(true) {
                System.out.println("대기");
                new Ex03(serv.accept()).start();
                System.out.println("접속됨");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

public class Ex03 extends Thread{
    InputStream is;
    OutputStream os;

    public Ex03(Socket sock) throws IOException {
        is = sock.getInputStream();
        os = sock.getOutputStream();
    }

    @Override
    public void run() {
        try{
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String msg = br.readLine();
            System.out.println(msg);
            msg = br.readLine();


            String[] arr = msg.split(" ");
            if(arr[1].equals("/")) arr[1] = "/index.html";
            File f = new File("./www" + arr[1]);
            InputStream is = new FileInputStream(f);
            os.write("HTTP/1.1 200 OK\n".getBytes());
            os.write("Content-Type: text/html; charset=UTF-8\n".getBytes());
            os.write("\n".getBytes());

            while(true) {
                int su = is.read();
                if(su == -1) break;
                os.write(su);
            }
            is.close();
            os.flush();
            os.close();
        } catch (IOException e) {
//            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        try(
                ServerSocket serv =  new ServerSocket(8080);
                ){
            while(true) {
                System.out.println("대기");
                new Ex03(serv.accept()).start();
                System.out.println("접속됨");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}