[Java] 네트워킹(Networking) #1.

bien·2024년 2월 11일
0

java

목록 보기
6/11

1. 네트워킹(Networking)

  • 네트워킹(networking)
    • 두 대 이상의 컴퓨터를 케이블로 연결하여 네트워크(networt)를 구성하는 것.
    • 컴퓨터들을 서로 연결하여 데이터를 손쉽게 주고받거나 또는 자원프린터와 같은 주변기기를 함께 공유하고자 하는 노력에서 시작되었다.
  • 전 세계의 셀 수도 없으만큼 많은 수의 컴퓨터가 인터넷이라는 하나의 거대한 네트워크를 구성하고 있다.
    • 인터넷을 통해 다양하고 방대한 데이터를 공유하는것이 가능해졌다.
  • 자바에서 제공하는 java.net 패키지를 활용하면 이러한 네트워크 어플리케이션의 데이터 통신 부분을 쉽게 작성할 수 있다.
    • 간단한 네트워크 애플리케이션은 단 몇 줄의 자바코드만으로도 작성이 가능하다.

1) 클라이언트 / 서버(client/server)

  • 서버 (Server)
    • 서비스를 제공하는 소프트웨어가 실행되는 컴퓨터(service provider)
    • 서비스: 서버가 클라이언트로부터 요청받은 작업을 처리하여 그 결과를 제공하는 것.
      • ex) 파일 서버(file server), 메일 서버(mail server), 어플리케이션 서버(application server)
  • 클라이언트 (client)
    • 서비스를 사용하는 컴퓨터 (service user)
  • 서버가 서비스를 제공하기 위해서는 서버프로그램이 있어야 하고 클라이언트가 서비스를 제공받기 위해서는 서버프로그램과 연결할 수 있는 클라이언트 프로그램이 있어야 한다.

네트워크 모델

  • 서버 기반 모델 (server-based model)
    • 네트워크 구성 시 전용 서버를 두는 것
      • 안정적인 서비스의 제공이 가능하다.
      • 공유 데이터의 관리와 보안이 용이하다.
      • 서버구축비용과 관리비용이 든다.
  • P2P 모델 (peer-to-peer model)
    • 별도의 전용서버 없이 각 클라이언트가 서버역할을 동시에 수행하는 것
      • 서버구축 및 운용비용을 절감할 수 있다.
      • 자원의 활용을 극대화할 수 있다.
      • 자원의 관리가 어렵다.
      • 보안이 취약하다.

2) IP주소 (IP address)

  • IP 주소
    • 컴퓨터(호스트, host)를 구별하는데 사용되는 고유한 값.
    • 인터넷에 연결된 모든 컴퓨터는 IP 주소를 갖는다.
    • 4byte (32bit)의 정수로 구성되어 있다.
      • 0~255(8bit).0~255.0~255.0~255
  • IP주소는 네트워크 주소호스트 주소로 나뉜다.
    • 네트워크 주소와 호스트 주소가 각각 몇 bit를 차지하는 지는 네트워크를 어떻게 구성했는지에 따라 달라진다.
    • 서로 다른 두 호스트의 IP 주소의 네트워크 주소가 같다는 것은, 두 호스트가 같은 네트워크에 포함되어 있다는 것을 의미한다.

  • IP주소와 서브넷 마스크를 비트연산자 &로 연산하면 IP 주소에서 네트워크 주소만을 뽑아낼 수 있다.
    • & 연산자는 bit의 값이 모두 1일 때만 1을 결과로 얻으므로 IP주소의 마지막 8bit는 모두 0이 된다.
    • 따라서 네트워크 주소는 24bit(192.168.10)이고, 호스트 주소는 마지막 8bit(1)임을 알 수 있다.
  • IP 주소에서 네트워크 주소가 차지하는 자리수가 많을 수록 호스트 주소의 범위가 줄어들기 때문에 네트워크의 규모가 작아진다.
    • 이 경우 호스트 주소의 자리수가 8자리이기 때문에 실제로는 네트워크에 포함 가능한 호스트 개수는 254개이다.
  • 호스트 주소가 0인 것은 네트워크 자신을 나타내고, 255는 브로드캐스트 주소로 사용되기 때문에 실제로 네트워크에 포함 가능한 호스트의 개수는 254개이다.

3) InetAddress

자바에서는 IP주소를 다루기 위한 클래스로 inetAddress를 제공하며 다양한 메서드를 제공하고 있다.

InetAddress 사용 예제

package _ch16;

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

public class NetworkEx1 {

	public static void main(String[] args) {
		InetAddress ip = null;
		InetAddress[] ipArr = null;
		
		try {
			ip = InetAddress.getByName("www.naver.com");
			System.out.println("getHostName() :" + ip.getHostName());
			System.out.println("getHostAddress() :" + ip.getHostAddress());
			System.out.println("toString() :" + ip.toString());
			
			byte[] ipAddr = ip.getAddress();
			System.out.println("getAddress() :" + Arrays.toString(ipAddr));
			
			String result = "";
			for (int i = 0; i < ipAddr.length; i++) {
				result += (ipAddr[i] < 0) ? ipAddr[i] + 256 : ipAddr[i];
				result += ".";
			}
			System.out.println("getAddress()+256 :" + result);
			System.out.println();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		
		try {
			ip = InetAddress.getLocalHost();
			System.out.println("getHostName() :" + ip.getHostName());
			System.out.println("getHostAddress() :" + ip.getHostAddress());
			System.out.println();
		} 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 (UnknownHostException e) {
			e.printStackTrace();
		}
		
	}
}

결과

getHostName() :www.naver.com
getHostAddress() :223.130.200.107
toString() :www.naver.com/223.130.200.107
getAddress() :[-33, -126, -56, 107]
getAddress()+256 :223.130.200.107.

getHostName() :mycom
getHostAddress() :172.30.1.51

ipArr[0] :www.naver.com/223.130.200.107
ipArr[1] :www.naver.com/223.130.195.200
  • 하나의 도메인명(www.naver.com)에 여러 IP주소가 매핑될 수 있고 또 그 반대의 경우도 가능하기 때문에 전자의 경우 getAllByName()을 통해 모든 IP주소를 얻을 수 있다.
  • getLocalHost() 를 통해 호스트명과 IP주소를 알아낼 수 있다.

4) URL(Uniform Resource Location)

  • URL(Uniform Resource Location)
    • 인터넷에 존재하는 여러 서버들이 제공하는 자원에 접근할 수 있는 주소를 표현하기 위한 것.
    • 프로토콜://호스트명:포트번호/경로명/파일명?쿼리스트링#참조
  • http://www.codechobo.com:80/sample/hello.html?referer=codechobo#index1
    • 프로토콜: 자원에 접근하기 위해 서버와 통신하는데 사용되는 통신 규약
      • http
    • 호스트명: 자원을 제공하는 서버의 이름
      • www.codechobo.com
    • 포트번호: 통신에 사용되는 서버의 포트번호
      • 80
    • 경로명: 접근하련느 자원이 저장된 서버상의 위치
      • /sample/
    • 파일명: 접근하려는 자원의 이름
      • hello.html
    • 쿼리(query): URL에서 '?' 이후의 부분
      • referer=codechobo
    • 참조(anchor): URL에서 '#' 이후의 부분
      • index1
  • 자바에서는 URL을 다루기 위한 클래스로 URL 클래스를 제공하며 다양한 메서드를 제공하고 있다.
  • URL 객체를 생성하는 방법은 다음과 같다.
URL url = new URL("http://www.codechobo.com:80/sample/hello.html?referer=codechobo#index1");
URL url = new URL("www.codechobo.com", "/sample/hello.html");
URL url = new URL("http", "www.codechobo.com", "/sample/hello.html");

URL 사용 예제

package _ch16;

import java.net.URL;

public class NetworkEx2 {

	public static void main(String[] args) throws Exception {
	    URL url = new URL("http://www.codechobo.com:80/sample/hello.html?referer=codechobo#index1");

	    System.out.println("url.getAuthority() : " + url.getAuthority());
	    System.out.println("url.getContent() : " + url.getContent());
	    System.out.println("url.getDefaultPort() : " + url.getDefaultPort());
	    System.out.println("url.getPort() : " + url.getPort());
	    System.out.println("url.getFile() : " + url.getFile());
	    System.out.println("url.getHost() : " + url.getHost());
	    System.out.println("url.getPath() : " + url.getPath());
	    System.out.println("url.getProtocol() : " + url.getProtocol());
	    System.out.println("url.getQuery() : " + url.getQuery());
	    System.out.println("url.getRef() : " + url.getRef());
	    System.out.println("url.getUserInfo() : " + url.getUserInfo());
	    System.out.println("url.toExternalForm() : " + url.toExternalForm());
	    System.out.println("url.toURI() : " + url.toURI());
	}

}

결과

url.getAuthority() : www.codechobo.com:80
url.getDefaultPort() : 80
url.getPort() : 80
url.getFile() : /sample/hello.html?referer=codechobo
url.getHost() : www.codechobo.com
url.getPath() : /sample/hello.html
url.getProtocol() : http
url.getQuery() : referer=codechobo
url.getRef() : index1
url.getUserInfo() : null
url.toExternalForm() : http://www.codechobo.com:80/sample/hello.html?referer=codechobo#index1
url.toURI() : http://www.codechobo.com:80/sample/hello.html?referer=codechobo#index1

5) URLConnection

  • URLConnection
    • 어플리케이션과 url 간의 통신연결을 나타내는 클래스의 최상위 클래스로, 추상클래스.
    • 구현체로 HttpURLConnectionJarURLConnection이 있다.
    • URL의 프로토콜이 http프로토콜인 경우 openConnection()은 HttpURLConnection을 반환한다.
    • URLConnection을 통해 사용해서연결하고자 하는 자원에 접근하고 읽기, 쓰기가 가능하다.
      • 그 외 관련된 정보를 읽고 쓸 수 있는 메서드가 제공된다.

URLConnection 사용 예시

package _ch16;

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

public class NetworkEx3 {

	public static void main(String[] args) {
		URL url = null;
		String address = "http://google.com";
		
		try {
			url = new URL(address);
			URLConnection conn = url.openConnection();
			
			System.out.println("conn.toString() : " + conn.toString());
	        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("getContentType() : " + conn.getContentType());
	        System.out.println("getDate() : " + conn.getDate());
	        System.out.println("getDefaultAllowUserInteraction() : " + conn.getDefaultAllowUserInteraction());
	        System.out.println("getDoInput() : " + conn.getDoInput());
	        System.out.println("getDoOutput() : " + conn.getDoOutput());
	        System.out.println("getExpiration() : " + conn.getExpiration());
	        System.out.println("getHeaderFields() : " + conn.getHeaderFields());
	        System.out.println("getIfModifiedSince() : " + conn.getIfModifiedSince());
	        System.out.println("getLastModified() : " + conn.getLastModified());
	        System.out.println("getReadTimeout() : " + conn.getReadTimeout());
	        System.out.println("getURL() : " + conn.getURL());
	        System.out.println("getUseCaches() : " + conn.getUseCaches());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

결과

conn.toString() : sun.net.www.protocol.http.HttpURLConnection:http://google.com
getAllowUserInteraction() : false
getConnectTimeOut() : 0
getContent() : sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@735b478
getContentEncoding() : null
getContentType() : text/html; charset=ISO-8859-1
getDate() : 1707649206000
getDefaultAllowUserInteraction() : false
getDoInput() : true
getDoOutput() : false
getExpiration() : 0
getHeaderFields() : {Transfer-Encoding=[chunked], null=[HTTP/1.1 200 OK], Server=[gws] ...
getIfModifiedSince() : 0
getLastModified() : 0
getReadTimeout() : 0
getURL() : http://www.google.com/
getUseCaches() : true

예제

package _ch16;

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

public class NetworkEx4 {

	public static void main(String[] args) {
		URL url = null;
		BufferedReader input = null;
		String address = "http://www.google.com";
		String line = "";
		
		try {
			url = new URL(address);
			input = new BufferedReader(new InputStreamReader(url.openStream()));
			
			while((line=input.readLine()) != null) {
				System.out.println(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
  • URL에 연결하여 그 내용을 읽어오는 예제이다.
    • 만약 URL이 유효하지 않으면 Malformed- URLException이 발생한다.
    • 읽어올 데이터가 문자데이터이기 때문에 BufferedReader를 사용했다.
    • outputStream()을 호출해 URL의 InputStrea을 얻은 이후로는 파일로부터 데이터를 읽는 것과 다르지 않다.
  • openStream()openConnection()을 호출해서 URLConnection을 얻은 다음 여기에 다시 getInputStream()을 호출한 것이다.
    • 즉, URL에 연결해서 InputStream을 얻어온다.
InputStream in = url.openStream();
// 위와 아래의 코드는 같은 작업을 수행한다.
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();

결과: 구글 페이지 일부 예시

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Google</title>
</head>
<body>
    <img src="https://www.google.com/images/branding/googlelogo/
    2x/googlelogo_light_color_92x30dp.png" alt="Google Logo">
</body>
</html>

url 페이지 다운로드 예제

package _ch16;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

public class NetworkEx5 {

	public static void main(String[] args) {
		URL url = null;
		InputStream in = null;
		FileOutputStream out = null;
		String address = "http://google.com";
		
		int ch = 0;
		
		try {
			url = new URL(address);
			in = url.openStream();
			out = new FileOutputStream("google.zip");
			
			while((ch=in.read()) != -1) {
				out.write(ch);
			}
			
			in.close();
			out.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
}
  • 이전 예제와 유사하나 텍스트 데이터가 아닌 이진 데이터를 읽어 파일에 저장한다는 점이 다르다.
    • 그래서 FileReader가 아닌 FileOutputStream을 사용했다.

결과


Reference

profile
Good Luck!

0개의 댓글