Node.JS 강좌 03편에서 맛보기로 Hello World 만을 리턴하는 웹서버를 만들어봤었습니다.
이번 강좌에서는 http 모듈을 이용해 더 기능이 향상된 웹서버과 웹클라이언트를 코딩해보도록 하겠습니다.
HTTP 서버 예제
우선 index.html 을 생성하세요.
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>
다음엔 server.js 를 작성하세요.
var http = require('http');
var fs = require('fs');
var url = require('url');
// 서버 생성
http.createServer( function (request, response) {
// URL 뒤에 있는 디렉토리/파일이름 파싱
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
// 파일 이름이 비어있다면 index.html 로 설정
if(pathname=="/"){
pathname = "/index.html";
}
// 파일을 읽기
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
// 페이지를 찾을 수 없음
// HTTP Status: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html'});
}else{
// 페이지를 찾음
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/html'});
// 파일을 읽어와서 responseBody 에 작성
response.write(data.toString());
}
// responseBody 전송
response.end();
});
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
클라이언트에서 서버에 접속을하면 URL에서 열고자 하는 파일을 파싱하여 열어줍니다.
파일이 존재하지 않는다면 콘솔에 에러 메시지를 출력합니다.
출력물
$ node server.js
Server running at http://127.0.0.1:8081/
Request for / received.
Request for /showmeerror received.
{ [Error: ENOENT: no such file or directory, open 'showmeerror']
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'showmeerror' }
Request for /index.html received.
서버를 실행하고 다음 링크들을 들어갔을때 뜨는 출력물입니다:
- http://127.0.0.1:8081/
- http://127.0.0.1:8081/showmeerror
- http://127.0.0.1:8081/index.html
HTTP 클라이언트 예제
var http = require('http');
// HTTPRequest의 옵션 설정
var options = {
host: 'localhost',
port: '8081',
path: '/index.html'
};
// 콜백 함수로 Response를 받아온다
var callback = function(response){
// response 이벤트가 감지되면 데이터를 body에 받아온다
var body = '';
response.on('data', function(data) {
body += data;
});
// end 이벤트가 감지되면 데이터 수신을 종료하고 내용을 출력한다
response.on('end', function() {
// 데이저 수신 완료
console.log(body);
});
}
// 서버에 HTTP Request 를 날린다.
var req = http.request(options, callback);
req.end();
14번과 19번 줄을 보면 response.on() 을 사용하죠. .on() 메소드, 익숙하지 않나요?
response 는 강좌 07편 Event Loop에서 봤었던 EventEmitter 클래스를 상속한 객체입니다.
출력물
$ node client.js
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>

