(Java) InetSocketAddress, HttpHandler 문법 및 사용

2021. 7. 5. 23:28Java

반응형

📕InetSocketAddress


InetSocketAddress에 관한 oracle 공식 문서를 보면 다음과 같다.

 

 

InetSocketAddress는 IP 소켓 주소(IP 주소 + 포트 넘버) 이다.

IP 소켓 주소 뿐만 아니라, hostname과 portname으로도 구성이 가능하다.

 

위의 경우를 코드로 한번 보자.

// If the port parameter is outside the range of valid port values, or if the hostname parameter is null.
// -> IllegalArgumentException will be occured


// 포트로만 구성
// 0 <= port value <= 65535
public InetSocketAddress(int port) {
	this(InetAddress.anyLocalAddress(), port);
}

//주소와 포트로 구성
// 0 <= port value <= 65535

public InetSocketAddress(InetAddress addr, int port) {
	holder = new InetSocketAddressHolder(
    				null, addr = null ? InextAddress.anyLocalAddress() : addr,
                    checkPort(port));
}


//hostname 과 port로 구성
public InetSocketAddress(String hostname, int port) {
	checkHost(hostname);
  	InetAddress addr = null;
    String host = null;
    try{
    	addr = IneAddress.getByName(hostname);
    } catch(UnknowHostException e) {
    	host = hostname;
    }
    holder = new InetSocketAddressHolder(host, addr, checkPort(port));
}

 

처음 CRUD를 공부하는 경우라면, 주로 localhost를 사용하기 때문에

포트만을 입력하면 되는 첫 번째 함수를 사용하게 될 것이다.

 

public class App{
	public static void main(String args[]) {
    	
        try{
            InetSocketAddress address = new InetSocketAddress(8000);
            HttpServer httpServer = HttpServer.create(address, 0);
            HttpHandler handler = new DemoHttpHandler();
            httpServer.createContext("/", handler);
            httpServer.start();
     	} catch(IOException e) {
        	e.pritnStackTrace();
        }
}

 

InetSocketAddress 를 통해서 주소를 localhost:8000번으로 설정한 후

HttpServer 를 통해서 주소와 System default value를 사용하기 위해 0을 넣어 준다.

 

그리고 여기서 handler가 등장하는데, handler는 path를 설정하는데 관여하며

CRUD에 직접적으로 영향을 미치는 녀석이다.

 

 

📕HttpHandler


그럼 이 HttpHandler는 "정확히" 뭐하는 녀석인가?

 

공식 문서에는 이렇게 적혀있다.

 

Ahandler which is invoked to process HTTP exchanges. Each HTTP exchange is handled by one of these handlers.

 

그러니까 HTTP의 교환을 처리하는 녀석인 것이다.

 

그럼 대체 어떤 교환을 말하는 것일까?

 

@Override

public void handle(HttpExchange exchange) throws IOException{

.....

}

 

이렇게 시작하는 handler는 저기 보이는 parameter exchange로 여러가지 교환을 할 수 있다.

대표적으로,

 

  • getRequetHeaders()
  • getResponseHeaders()
  • getRequestURI
  • getRequestBody()
  • getRequestMethod()

가 있다.

 

getRequestURI는 서버의 URI를 가져와서 URI 클래스의 변수에 저장하면,

path를 가져오는데 사용할 수 있다.

URI uri = exchange.getRequestURI();
String path = uri.getPath();

 

그리고 이렇게 얻은 path를 통해서 처리하는 작업을 세분화 할 수 있는 것이다.

 

getRequestMethod()는 CRUD의 작업자체를 장관한다고 볼 수 있다.

String requestMethod = exchange.getRequestMethod();

if(requestMethod.equals("GET")) {
	....
}

if(requestMethod.equals("POST") {
	...
}

....

 

이처럼 GET이 들어왔을때, POST가 들어왔을때 어떻게 처리할지를 지정해줄 수 있다.

 

하지만 단순히 handler에서 지정했다고 해서 실제로 서버에서 처리되는 것은 아니기 때문에

다른 무언가가 필요하다.

 

그 무언가는 다음 글에서 적도록 하겠다.

반응형

'Java' 카테고리의 다른 글

logging이란?  (0) 2022.02.23
(Java) JDBC란?  (0) 2022.02.20
JAVA - JVM에 대해 알아보자 -1  (0) 2022.02.18
Java ClassLoader(클래스로더)에 관한 기본적인 이해 -1  (0) 2022.02.18
(JPA) JPA가 뭐야?? 이거 왜 쓰는거야?  (0) 2021.11.18