[익명 채팅]node.js + socket.io 이용 Javascript & HTML & CSS/node.js2016. 8. 11. 19:04
사전 준비
node.js 설치(npm 설치)
socket.io 설치
서버 코드(server.js)
var http = require('http'); var fs = require('fs'); var socketio = require('socket.io'); var server = http.createServer(function(req, res){ fs.readFile('client.html', 'utf8', function(error, data){ res.writeHead(200, {'Content-Type':'text/html; charset=UTF-8'}); res.end(data); }); }).listen(3000, function(){ }); var io = socketio.listen(server); io.sockets.on('connection', function(socket){ socket.on('toServer', function(data){ socket.broadcast.emit('toClient', data); }); }); |
서버로 클라이언트가 connection을 해오면 해당 소켓에 toServer라는 이벤트를 바인딩해 준다.
toServer라는 이벤트가 발생하면 broadcast로 모든 클라이언트에게 뿌려 준다.
클라이언트 코드(client.html)
<html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script src="/socket.io/socket.io.js"></script> <style> #result{ width:400px; height:300px; background-color:darkgray; border-style:solid; border-width:1px; } </style> </head> <body> <div id="result"></div> <input id="input"> <button>Enter</button> <script> $(function(){ var socket = io.connect(); $("button").on("click", function(data){ $('#result').append('<div>나:'+$('#input').val()+'</div>'); socket.emit('toServer', $('#input').val()); $("#input").val(''); checkOverFlowBox(); });
socket.on('toClient', function(data){ $('#result').append('<div>익명:'+data+'</div>'); checkOverFlowBox(); });
$("input").on("keydown", function(e){ if(e.keyCode == 13){ $("button").trigger("click"); } }); });
//줄 수 체크 var checkOverFlowBox = function(){ divLength = $('#result > div').length; if(divLength >= 15){ $('#result > div').first().remove(); } }; </script> </body> </html> |
/socket.io/socket.io.js는 저절로 만들어짐.
저걸 쓰거나 아니면 socket.io의 클라이언트용 cdn을 써도 된다.
script src로 socket.io 사용준비를 끝냈으면 이제 io.connect()이 반환해주는 Socket객체가 가지고 있는 emit(서버로 전송)과 on(서버로부터 수신)을 사용할 수 있다.
뼈대가 되는 코드만 저장해두려고 작성함.
인터페이스와 디자인은 무시!
'Javascript & HTML & CSS > node.js' 카테고리의 다른 글
node.js 프로젝트 실행 순서(어느정도 익숙해진 후 재정리) (0) | 2016.08.12 |
---|---|
[socket.io] 요약 (0) | 2016.08.11 |
[express 프레임워크] 요약 (0) | 2016.08.11 |
[외부 모듈] jade 모듈 (템플릿 엔진) (0) | 2016.08.10 |
[외부 모듈] ejs 모듈 (템플릿 엔진 모듈) (0) | 2016.08.10 |