Socket.io
Javascript를 이용하여 실시간 어플리케이션을 구축할 수 있도록 하는 엔진.
양 방향의 이벤트 기반의 통신이 가능하고, 모든 플렛폼과 장치에서 동작
기본적인 socket.io 서버
socketio_server.js
// socketio_server.js var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); server.listen(80); app.get('/', function(req, res) { res.sendFile(__dirname + '/sample1.html'); }); io.on('connection', function(socket) { // 접속한 모든 클라이언트에 전달 socket.emit('news', { hello: 'world' }); // Client로 부터 수신받는 event socket.on('feedback', function(data) { console.log(data); }); });
sample1.html
<!-- sample1.html --> <script src="/socket.io/socket.io.js"></script><p> </p><script> var socket = io(); socket.on('news', function(data) { document.write(JSON.stringify(data)); socket.emit('feedback', { hello : 'world2' }); }); </script>
socket.io를 이용한 간단한 채팅 서버
s_chat_server.js
// s_chat_server.js var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); server.listen(80); // 기본 접속 경로 app.get('/', function(req, res) { res.sendFile(__dirname + '/sample2.html'); }); // 첫번째 접속 var sock = undefined; // 외부 접속시 처리 io.on('connection', function(socket) { // 접속한 모든 클라이언트에 전달 socket.emit('news', { hello: 'world1' }); if( !sock) { sock = socket; } // Broadcast socket.on('broadcast', function(data) { console.log('Broadcast: ' + data); socket.broadcast.emit('msg', data); }); // Unicast socket.on('unicast', function(data) { console.log('Unicast: ' + data); socket.emit('msg', data); }); // Send All! socket.on('sendall', function(data) { console.log('Sendall: ' + data); io.emit('msg', data); }); });
sample2.html
<!-- sample2.html --> <html> <head> <title>Hello Pi!</title> <script src='https://code.jquery.com/jquery-3.1.1.min.js'></script> <script src='/socket.io/socket.io.js'></script> <script> $(function() { var socket = io(); var id = 'Guest..' + Math.floor((Math.random() * 10) + 1); socket.on('msg', function(data) { $('#msgs').append($('<p>').text('ID: ' + data.id + ': ' + data.msg)); }); var sendMsg = function(type) { var msg = $('input').val(); $('#msgs').append($('<p>').text('ME: ' + id + ': ' + msg)); socket.emit(type, { id: id, msg: msg}); $('input').val(''); } $('#unicast').click(function() { sendMsg('unicast'); }); $('#broadcast').click(function() { sendMsg('broadcast'); }); $('#sendall').click(function() { sendMsg('sendall'); }); }); </script> </head> <body> <input type='text' /> <p/> <button id='unicast'>Unicast</button> <button id='broadcast'>Broadcast</button> <button id='sendall'>Sendall</button> <div id='msgs'/> </body> </html>
'Node.js' 카테고리의 다른 글
Jade 이해하기 (0) | 2017.02.02 |
---|---|
HTTP 요청, 응답 이해하기(Express 프로젝트 기준) (0) | 2017.02.01 |
npm, express (0) | 2016.11.18 |