양방향 통신을 지원하는 WebSocket을 이용해서 이것저것 해보려하는데 기본적인 echo 테스트부터 막혔다.
클라이언트(front-end)쪽 코드는 간단해서 구현하기 쉬웠지만 문제는 서버쪽(back-end)이었다.
내가 참고한 책(프로 HTML5 프로그래밍)에 나와있는 코드대로 해도 실행이 잘 되지않아 제대로 된 서버를 구하기로 했다.
참고로 내가 테스트한 환경은 다음과 같다.
서버 - Redhat linux 2.6.32
웹브라우저 - 구글 크롬
WebSocket server를 구동시키기 위해 Node.js를 사용한다.
Node.js 설치
Node.js는 서버측에서 사용되는 javascript 엔진이다. 일단 요놈이 필요하다.
Node.js 홈페이지에 가면 구할 수 있다. 다운로드를 클릭한 후 압축된 source code 주소를 복사해두자.
다음과 같이 서버에 다운받고 설치를 해둔다.
shell> wget http://nodejs.org/dist/v0.6.19/node-v0.6.19.tar.gz
shell> tar xvzf node-v0.6.19.tar.gz
shell> cd node-v0.6.19
shell> ./configure
shell> make
shell> make install
WebSocket 모듈설치
Node.js에는 기본적으로 WebSocket 모듈이 들어있지 않은 모양이다. 그래서 따로 설치를 해줘야 한다.
모듈 설치에는 npm(Node Package Manager)이라는 것을 사용하면 편하다.
다음과 같이 npm과 WebSocket 모듈을 설치할 수 있다. npm은 /usr/local/bin에 설치된다.
shell> curl http://npmjs.org/install.sh | sh
shell> cd /usr/local/bin
shell> ./npm install websocket
WebSocket echo Front/Back-end script
이제 필요한 준비가 모두 끝났다. 구미에 맞는 서버를 구현해서 띄워놓고 테스트를 해보자.
/usr/local/bin에 다음 파일을 만들어둔다.
ws_server.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 | #!/usr/bin/env node var WebSocketServer = require( 'websocket' ).server; var http = require( 'http' ); 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); console.log((new Date()) + ' Connection accepted. '); connection.on(' message ', function(message) { if (message.type === ' utf8 ') { console.log(' Received Message: ' + message.utf8Data); connection.sendUTF(message.utf8Data); } else if (message.type === ' binary ') { console.log(' Received Binary Message of ' + message.binaryData.length + ' bytes '); connection.sendBytes(message.binaryData); } }); connection.on(' close ', function(reasonCode, description) { console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); }); }); |
다음과 같이 Front-end script를 구현한다. (반드시 Back-end 코드와 같은 위치에 있을 필요는 없다)
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 | <!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); } } </script> <input type= "text" id= "inputMessage" value= "Hello, Web Socket!" ><button id= "sendButton" >Send</button> <pre id= "output" ></pre> |
코드를 보면 알 수 있듯이 Front-end 코드는 거의 해줄게 없다.
WebSocket 객체에 onopen, onmessage, onclose callback 함수만 걸어놓고 그 안에서 필요한 처리만 해주면 된다.
테스트
Front-end 파일(websocket.html)이 있는 곳에서 다음과 같이 웹 서버를 실행한다.
웹서버로는 python으로 구현된 SimpleHTTPServer를 이용했다. (기본설치되어 있었음. 없으면 설치해야....)
python -m SimpleHTTPServer 8888
그리고, Back-end(ws_server.js) 파일이 있는 곳에서 자신이 만든 echo 서버를 실행시킨다.
./node ws_server.js
이제 웹 브라우저를 열고 들어가보자.
위와같이 잘 되면 성공이다. :)
* 참고 URL
2. npm소스코드가 있는곳. 유용한 명령도 있다.
'프로그래밍 > HTML5' 카테고리의 다른 글
[HTML5] PeerConnection을 이용한 1:1 영상통화 구현 (4) | 2012.06.25 |
---|---|
[HTML5] WebSocket을 이용한 초간단 채팅 (0) | 2012.06.20 |
[HTML5] 위치정보 사용하기 (0) | 2012.06.18 |
[HTML5] 캠(cam) 이용하기 (0) | 2012.06.04 |
[HTML5] jWebSocket 이용하기 (0) | 2012.06.01 |