웹소켓 서버를 구현한 라이브러리는 다음이 있다.
1) node.js : websocket-node ( https://github.com/Worlize/WebSocket-Node )
2) ANSI C : libwebsockets ( http://git.warmcat.com/cgi-bin/cgit/libwebsockets/ )
3) Java : Jetty ( http://webtide.intalio.com/2011/04/getting-started-with-websockets/ )
이번 포스팅에서는 node.js에서 구현된 사례를 알아보겠다. https://github.com/Worlize/WebSocket-Node 에서 가이드 된 것처럼 node.js 라이브러리를 설치한다. 그리고 서버 예제를 실행한다.
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('echo-protocol', 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.'); }); }); |
클라이언트는 다음과 같이 HTML을 작성한다.
<!DOCTYPE html> <title> WebSocket Image Drop</title> <h1> Set Image </h1> <div id="output"></div> <script> function setup(){ output=document.getElementById("output"); var ws=new WebSocket("ws://localhost:8080",['echo-protocol']); ws.onopen=function(e){ console.log("Connected"); } ws.onclose=function(e){ console.log("Closed"); } ws.onerror=function(e){ console.log("Error"); console.log(e); } ws.onmessage=function(e){ var blob=e.data; console.log("Message Received Size:"+blob.Size); if(window.webkitURL){ URL=webkitURL; } var uri=URL.createObjectURL(blob); var img=document.createElement("img"); img.src=uri; document.body.appendChild(img); } document.ondrop=function(e){ document.body.style.backgroundColor="#fff"; try{ e.preventDefault(); handleFileDrop(e.dataTransfer.files[0]); return false; } catch(err){ console.log(err); } } document.ondragover=function(e){ e.preventDefault(); document.body.style.backgroundColor="#6fff41"; } document.ondragleave=function(e){ document.body.style.backgroundColor="#fff"; } function handleFileDrop(file){ var reader=new FileReader(); reader.readAsArrayBuffer(file); reader.onload=function(){ console.log('transfer:'+file.name); ws.send(reader.result); } } } setup(); </script> |
서버를 실행하고 브라우저에서 그림 파일 하나를 drag-drop 하면 다음과 같은 결과가 나타난다.
1) 서버 사이드
2) 브라우저 사이트