블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

2012. 12. 22. 14:46 NodeJS/Prototyping

Node.js에서 Express.js를 사용하고 템플릿 엔진은 Jade를 사용한다. 이때 socket.io를 간단히 테스트 해보자 


> 먼저 Socket.io 모듈를 설치한다 (물론 express 모듈도 사전 설치되었다 가정한다)

npm install socket.io


> Express.js를 통하여 만들고자 하는 컨텍스트를 만든다

express day3


> day3 디렉토리로 이동을 하면 app.js 파일이 있고 해당 파일안에 socket.io 모듈를 넣고 http 모듈과 체인닝을 해준다. 그리고 jade 설정이 되어 있는 socketio.js 모듈을 로딩한다 

// app.js 파일 상단 코딩

// 기존 코드 

var express = require('express')

  , routes = require('./routes')  // index.js 파일 

  , user = require('./routes/user') // user.js 파일 

  , dowon = require('./routes/dowon')// dowon.js 파일 

  , http = require('http')

  , path = require('path');


// 변경 코드 

var express = require('express');

var app = express()

  , http = require('http').createServer(app)   

  , io = require('socket.io').listen(http)  // http 모듈을 socket.io 모듈과 체인닝함 

  , routes = require('./routes')

  , user = require('./routes/user')

  , socketio = require('./routes/socketio') // socketio.js 파일 로딩 

  , path = require('path');


> url rout 설정을 해줌 for jade

// url route

app.get('/', routes.index);

app.get('/users', user.list);

app.get('/socketio', socketio.io); //  브라우져에서 /socketio 호출하면 socketio 모듈의 io exports명칭의 펑션을 호출한다


> socketio.jade 파일을 만들어서 views 디렉토리에 놓는다 

// socketio.jade 파일 내역

doctype 5

html

  head

    title= title

    link(rel='stylesheet', href='/stylesheets/style.css')

    script(src='/socket.io/socket.io.js')

    script(src='http://code.jquery.com/jquery-1.8.3.min.js')

    script

        $(function() {

            var ws = io.connect();  // node에서 수행한 app.js의 socket.io listen으로 연결


            ws.emit('server_1');  // 서버쪽으로 server_1 이벤트 발행

            ws.on('client_1', function(msg) {  // 서버로부터 온 client_1 이벤트 처리 

                $('#container').html(msg);

            });

        });

  body

    h1= title

    div#container


> app.js 파일안에 socket.io 서버 코딩을 한다

// socket on

io.sockets.on('connection', function(socket) {

    console.log('server connection');


    socket.on('server_1', function(data) { // 클라이언트로 부터 온 server_1 이벤트 처리

        if(data != undefined) {

            console.log('>>>>>' + data);

        }


        var msg = 'hi youngsik';

        socket.emit('client_1', msg); // 클라이언트쪽으로 client_1 이벤트 발행

    });

});


> 브라우저에서 호출한다 그러면 잠시후 브라우져에서 "hi youngsik" 메세지가 div(id=container)에 뿌려진다


* 테스트 전체 파일

express_socketio.zip


* Socket.io GitHub : 자세한 사용 설명 보기

posted by 윤영식