node.js¿Í npmÀÌ ¼³Ä¡µÈ »óÅ¿¡¼ npm install socket.io ·Î ½ÃÀÛÇÕ´Ï´Ù.
±× ´ÙÀ½¿£ ¾î¼¶ó°í ÀÔ´Ï´Ù.
Á൵ ¸ø ¸Ô°Ú½À´Ï´Ù.
±×·¡¼ ½±°Ô Á¤¸®¸¦ ÇÏ·Á°í Outsider´Ô Ã¥º¸¸é¼ Á¤¸®ÇÏ·Á°í ÇÕ´Ï´Ù.
¼Ò½º°¡ ÀÖ½À´Ï´Ù. ¾Æ¹« À̽´¾ø½À´Ï´Ù. ^^b
Ã¥ÀÇ Ã¹ ¿¹Á¦´Â ±â¸¦ Á×ÀÔ´Ï´Ù. ÇÑ 199 ÆäÀÌÁö°¡ ´Ù ¼Ò½º.
npm install socket.io °¡ µÇ¸é
app.js ÆÄÀÏÀ» ¸¸µì´Ï´Ù. ¼¹ö¿¡¼ µ¹¾Æ°¡´Â javascriptÀÔ´Ï´Ù.
----
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
----
±×¸®°í Ŭ¶óÀÌ¾ðÆ®¿¡¼ µ¹¾Æ°¡´Â index.html ÀÔ´Ï´Ù.
----
<script src="/socket.io/socket.io.js"></script>
<script>
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
----
Æú´õ¸¦ º¸¸é ´ÙÀ½°ú °°ÀÌ ÀÖ½À´Ï´Ù.
app.js
index.html
node_modules/
ÀÌÁ¦ ´ÙÀ½ ¸í·É¾î·Î ¼¹ö¸¦ ¶ç¿ì¸é µË´Ï´Ù.
node app.js
80Æ÷Æ®·Î ¶ß±â ¶§¹®¿¡ root±ÇÇÑÀÌ ÇÊ¿äÇÕ´Ï´Ù. ±ÇÇÑÀÌ ¾ø´Â °æ¿ì ´ÙÀ½°ú °°Àº ¿¡·¯°¡ ¹ß»ýÇÕ´Ï´Ù.
gwang-nam-heoyi-macbook-pro:socket.io kenu$ node app.js
info - socket.io started
warn - error raised: Error: listen EACCES
gwang-nam-heoyi-macbook-pro:socket.io kenu$
sudo node app.js
¸®´ª½º¿Í ¸ÆÀº ÀÌ·¸°Ô ½ÇÇàÇÏ¼Å¾ß ÇÒ °ÍÀÔ´Ï´Ù.
¼¹öÂÊ¿¡ ´ÙÀ½°ú °°ÀÌ ·Î±×°¡ ¿Ã¶ó¿É´Ï´Ù.
gwang-nam-heoyi-macbook-pro:socket.io kenu$ sudo node app.js
Password:
info - socket.io started
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized 21130281791178129285
debug - setting request GET /socket.io/1/websocket/21130281791178129285
debug - set heartbeat interval for client 21130281791178129285
debug - client authorized for
debug - websocket writing 1::
debug - websocket writing 5:::{"name":"news","args":[{"hello":"world"}]}
{ my: 'data' }
±×¸®°í Ŭ¶óÀÌ¾ðÆ® ºê¶ó¿ìÀúÀÇ ÄܼÖÀ» º¸¸é ´ÙÀ½°ú °°Àº ÄÜ¼Ö ·Î±×¸¦ º¼ ¼ö ÀÖ½À´Ï´Ù.
Object
hello: "world"
__proto__: Object
¼¹öÀÇ ¸Þ½ÃÁö{"hello":"world"}°¡ Ŭ¶óÀÌ¾ðÆ®·Î, Ŭ¶óÀ̾ðÆ®ÀÇ ¸Þ½ÃÁö{my:'data'}°¡ ¼¹ö·Î Àü¼ÛµÇ¼ ·Î±×¿¡ ÂïÈù °ÍÀ» È®ÀÎÇÒ ¼ö ÀÖ½À´Ï´Ù.
¼¹öÀÇ ·Î±×¸¦ º¸½Ã¸é °è¼Ó ÁÖ±âÀûÀ¸·Î ½ÉÀå¹Úµ¿(heartbeat)À» È®ÀÎÇÏ´Â ·Î±×°¡ ¿Ã¶ó°¡´Â °ÍÀ» º¼ ¼ö ÀÖ½À´Ï´Ù.
Å©·Ò ºê¶ó¿ìÀú Console¿¡¼ socket.emit('my other event', {my:'okjsp message'}); ÀÔ·ÂÇÏ¸é ¼¹öÂÊ¿¡ Àü¼ÛµÈ ¸Þ½ÃÁö ·Î±×°¡ ÂïÈü´Ï´Ù.
ÀÌÈÄ´Â Outsider´ÔÀÇ Ã¥À» Âü°í·Î ÇØ¼ ¿øÇÏ´Â ½ÃÁ¡¿¡ ¸Þ½ÃÁö¸¦ ÁÖ°í ¹ÞÀ» ¼ö ÀÖµµ·Ï Äڵ带 °³¼±½ÃÄÑ ³ª°¡º¸°Ú½À´Ï´Ù.
to be continued...