WebSocket echo 테스트 코드를 조금만 수정하면 아주 간단한 채팅 어플을 만들 수있다. 


이런것이 모두 web에서 가능하다는 것!!


back-end script (broadcast.js)

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)

<!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 = [];

    url = "ws://192.168.25.114:8080";
    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


웹브라우저 창을 두개 열고 접속해서 테스트해보면 된다.



Posted by DevMoon
,