WebSocket echo 테스트 코드를 조금만 수정하면 아주 간단한 채팅 어플을 만들 수있다.
이런것이 모두 web에서 가능하다는 것!!
back-end script (broadcast.js)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | var WebSocketServer = require( 'websocket' ).server; var http = require( 'http' ); var clients = []; // 임의로 ID부여하기 위함 var idlist = []; var id = 0; var server = http.createServer( function (request, response) { console.log(( new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(8080, function () { console.log(( new Date()) + ' Server is listening on port 8080' ); }); wsServer = new WebSocketServer({ httpServer: server, // You should not use autoAcceptConnections for production // applications, as it defeats all standard cross-origin protection // facilities built into the protocol and the browser. You should // *always* verify the connection's origin and decide whether or not // to accept it. autoAcceptConnections: false }); function originIsAllowed(origin) { // put logic here to detect whether the specified origin is allowed. return true ; } wsServer.on('request ', function(request) { if (!originIsAllowed(request.origin)) { // Make sure we only accept requests from an allowed origin request.reject(); console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected. '); return; } var connection = request.accept(null, request.origin); clients.push(connection); // 임의로 id값을 할당함. request.key값으로 client 구분 idlist[request.key] = id++; console.log((new Date()) + ' Connection accepted. '); connection.on(' message ', function(message) { if (message.type === ' utf8 ') { console.log(' Received Message: ' + message.utf8Data); // 브로드캐스팅!! clients.forEach(function(cli) { msg = idlist[request.key]+ ' : ' +message.utf8Data; cli.sendUTF(msg); }); } else if (message.type === ' binary ') { console.log(' Received Binary Message of ' + message.binaryData.length + ' bytes '); } }); connection.on(' close ', function(reasonCode, description) { console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); }); }); |
front-end script (websocket.html)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | <!DOCTYPE html> <title>WebSocket Test Page</title> <script> var log = function (s) { console.log(s); if (document.readyState !== "complete" ) { log.buffer.push(s); } else { document.getElementById( "output" ).innerHTML += (s + "\n" ) } } log.buffer = []; w = new WebSocket(url); w.onopen = function () { log( "open" ); w.send( "thank you for accepting this Web Socket request" ); } w.onmessage = function (e) { console.log(e.data); log(e.data); } w.onclose = function (e) { log( "closed" ); } window.onload = function () { log(log.buffer.join( "\n" )); document.getElementById( "sendButton" ).onclick = function () { console.log(document.getElementById( "inputMessage" ).value); w.send(document.getElementById( "inputMessage" ).value); } // 간지나게 엔터키 누르면 메시지 날림 document.getElementById( "inputMessage" ).onkeypress = function () { if (event.keyCode == '13' ) { value = document.getElementById( "inputMessage" ).value w.send(value); document.getElementById( "inputMessage" ).value = "" ; } } } </script> <input type= "text" id= "inputMessage" > <button id= "sendButton" >Send</button> <pre id= "output" ></pre> |
echo 예제와 마찬가지로 server 돌려주고 웹으로 접속. 끄읕!!
shell> python -m SimpleHTTPServer 8888
shell> ./node broadcast.js
웹브라우저 창을 두개 열고 접속해서 테스트해보면 된다.
'프로그래밍 > HTML5' 카테고리의 다른 글
[HTML5] WebRTC 기능을 이용한 영상채팅 시스템 구현 (2) | 2012.07.20 |
---|---|
[HTML5] PeerConnection을 이용한 1:1 영상통화 구현 (4) | 2012.06.25 |
[HTML5] WebSocket echo 테스트 / 서버설치 (0) | 2012.06.20 |
[HTML5] 위치정보 사용하기 (0) | 2012.06.18 |
[HTML5] 캠(cam) 이용하기 (0) | 2012.06.04 |