728x90
java.net

 

서버와 클라이언트

  • 서버 : 서비스를 제공하는 컴퓨터
  • 클라이언트 : 서버가 제공한 서비스를 받는 컴퓨터
      
  • 서버 모델 : 전용 서버를 두고 그 서버의 서비스를 받는다.
  • P2P 모델 : 클라이언트가 서버의 역할을 동시에 수행하는 것.
      

네트워크

  • 네트워크 : 두대 이상의 컴퓨터를 케이블로 연결하여 네트워크를 구성 

  • IP : 네트워크 상에서 고유한 자신의 주소
    • 공인 : 어디에서던지 접속할 수 있는 주소
    • 내부 : 내부에서만 통용되는 주소. (192.168.0.10)
  • 포트 : 
    ex)
    • ftp 21
    • web 80
    • mariadb 3306
    • mail 25

예제 1. 

<NetStream>

네이버 서버 프로그램 구현

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class Net02 {
	public static void main(String[] args) {
		
		URL url = null;
		BufferedReader br = null;
		String addr = "https://www.naver.com";
		
		try {
			url = new URL(addr);
			InputStream is = url.openStream();
			br = new BufferedReader(new InputStreamReader(is));
			String line = "";
			while (    (line = br.readLine()) != null    ) {
				System.out.println(line);
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

예제 2.

<InetAddress>

호스트명, 호스트주소 받아오기

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;

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

		InetAddress ip = null;
		InetAddress[] ipArr = null;

		try {
			// https:// 없이 작성
			ip = InetAddress.getByName("www.naver.com");
			System.out.println("getHostName : " + ip.getHostName());
			System.out.println("getHostAddr : " + ip.getHostAddress());
			System.out.println("ip를 문자열로 반환 : " + ip.toString());

			byte[] ipAddr = ip.getAddress();
			System.out.println("getAddress : " + Arrays.toString(ipAddr));
			// ip : 0 ~ 255
			String result = "";
			for (int i = 0; i < ipAddr.length; i++) {
//				if (ipAddr[i] < 0) {
//					result += ipAddr[i] + 256;
//				} else {
//					result += ipAddr[i];
//				}
//				result += ".";
				// 위의 방식을 간략히 표현한것이 아래방식
				result += (ipAddr[i] < 0 ? ipAddr[i] + 256 : ipAddr[i]);
				result += ".";
			}
			System.out.println("변경된 IP : " + result);

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

		// 내 IP 출력하기
		try {
			ip = InetAddress.getLocalHost();
			System.out.println("getHostName : " + ip.getHostName());
			System.out.println("getHostAddr : " + ip.getHostAddress());
			System.out.println("ip를 문자열로 반환: " + ip.toString());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		
		try {
			ipArr = InetAddress.getAllByName("www.naver.com");
			for (int i = 0; i < ipArr.length; i++) {
				System.out.println("ipArr[" + i + "] : " + ipArr[i]);
			}
		} catch (Exception e) {

		}

	}
}

[실행결과]

getHostName : www.naver.com
getHostAddr : 125.209.222.141
ip를 문자열로 반환 : www.naver.com/125.209.222.141
getAddress : [125, -47, -34, -115]
변경된 IP : 125.209.222.141.
getHostName : DESKTOP-6I8DHJ9
getHostAddr : 192.168.56.1
ip를 문자열로 반환 : DESKTOP-6I8DHJ9/192.168.56.1
ipArr[0] : www.naver.com/125.209.222.141
ipArr[1] : www.naver.com/125.209.222.142

예제 3.

<URLConnection>

URLConnection 객체의 속성들을 .get( ) 메소드를 이용해 불러올 수 있다.

import java.net.URL;
import java.net.URLConnection;

public class Net04 {
	public static void main(String[] args) {
		
		URL url = null;
		
		try {
			url = new URL("https://www.clien.net/service/board/news/16278279?od=T31&po=1&category=0&groupCd=");
			URLConnection conn = url.openConnection();
			System.out.println("conn : " + conn);
			System.out.println("getAllowUserInteraction : " + conn.getAllowUserInteraction());
			System.out.println("getConnectTimeOut() : " + conn.getConnectTimeout());
			System.out.println("getContent : " + conn.getContent() );
			System.out.println("getContentEncoding : " + conn.getContentEncoding());
			System.out.println("getDate() : " + conn.getDate());
			System.out.println("getDefaultUserCaches : " + conn.getUseCaches());
			System.out.println("getContentType : " + conn.getContentType());
			System.out.println("getDoInput(): "+ conn.getDoInput());
			System.out.println("getExpiration : " + conn.getExpiration() );
			System.out.println("getHeaderField : " + conn.getHeaderFields());
			System.out.println("getIfModifiedSince : " + conn.getIfModifiedSince());
			System.out.println("getLastModified : " + conn.getLastModified());
			System.out.println("getURL : " + conn.getURL());
			System.out.println("getUserCache : " + conn.getUseCaches());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

[실행결과]

conn : sun.net.www.protocol.https.DelegateHttpsURLConnection:https://www.clien.net/service/board/news/16278279?od=T31&po=1&category=0&groupCd=
getAllowUserInteraction : false
getConnectTimeOut() : 0
getContent : sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@40005471
getContentEncoding : null
getDate() : 1627955209000
getDefaultUserCaches : true
getContentType : text/html;charset=UTF-8
getDoInput(): true
getExpiration : 0
getHeaderField : {Transfer-Encoding=[chunked], null=[HTTP/1.1 200 OK], Server=[Apache], X-Content-Type-Options=[nosniff, nosniff], Date=[Tue, 03 Aug 2021 01:46:49 GMT], X-Frame-Options=[DENY, DENY], Strict-Transport-Security=[max-age=63072000; includeSubDomains; preload], Cache-Control=[no-transform, private, max-age=0], Vary=[Accept-Encoding], Set-Cookie=[SESSION=ec5943f9-1ab5-44fd-a94f-6d28d671af4d; Path=/service/; HttpOnly, SCOUTER=xqku1kkokp7c6; Expires=Sun, 21-Aug-2089 05:00:56 GMT; Path=/, SCOUTER=x2s1b4s51lcu7s; Expires=Sun, 21-Aug-2089 05:00:56 GMT; Path=/], X-XSS-Protection=[1; mode=block], Content-Language=[ko-KR], Content-Type=[text/html;charset=UTF-8]}
getIfModifiedSince : 0
getLastModified : 0
getURL : https://www.clien.net/service/board/news/16278279?od=T31&po=1&category=0&groupCd=
getUserCache : true

예제 4.

<URL>

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

public class Net05 {
	public static void main(String[] args) {
		try {
//			/URL url = new URL("https://docs.oracle.com/en/java/javase/11/docs/api/index.html");
			URL url = new URL("https://www.clien.net/service/board/news/16281434?od=T31&po=0&category=0&groupCd=");
			System.out.println("urlgetAuthority" + url.getAuthority());
			System.out.println("getContent :" + url.getContent());
			System.out.println("getDefaultPort :" + url.getDefaultPort());
			System.out.println("getFile :" + url.getFile());
			System.out.println("getHost :" + url.getHost());
			System.out.println("getPath :" + url.getPath());
			System.out.println("getProtocol:" + url.getProtocol());
			System.out.println("getQuery :" + url.getQuery());
			System.out.println("getRef :" + url.getRef());
			System.out.println("getUserInfo :" + url.getUserInfo());
			System.out.println("toExternalForm :" + url.toExternalForm());
			System.out.println("toURI :" + url.toURI());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}

[실행결과]

urlgetAuthoritywww.clien.net
getContent :sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@40005471
getDefaultPort :443
getFile :/service/board/news/16281434?od=T31&po=0&category=0&groupCd=
getHost :www.clien.net
getPath :/service/board/news/16281434
getProtocol:https
getQuery :od=T31&po=0&category=0&groupCd=
getRef :null
getUserInfo :null
toExternalForm :https://www.clien.net/service/board/news/16281434?od=T31&po=0&category=0&groupCd=
toURI :https://www.clien.net/service/board/news/16281434?od=T31&po=0&category=0&groupCd=

'JAVA' 카테고리의 다른 글

jQuery 연결하기  (0) 2021.08.09
소켓 (Socket)  (0) 2021.08.03
GUI  (0) 2021.08.01
스레드 (Thread)  (0) 2021.08.01
한글깨짐 오류  (0) 2021.07.30

+ Recent posts