[Node.js] websocket 모듈을 통한 에코 서버 구축하기

류명운

·

2016. 2. 26. 01:21

반응형

[Node.js] websocket 모듈을 통한 에코 서버 구축하기


* 사전에 미리 node.js가 설치되어 있어야 합니다.

* 참고 : http://myeonguni.tistory.com/1388



1. websocket 모듈 설치하기


-> websocket 모듈을 설치할 폴더를 생성해줍니다. (ex - c:\wsServer)


-> 시작(윈도우키) + R -> cmd 입력 후 엔터



-> websocket 모듈을 설치할 폴더로 포커스를 이동 - "cd c:\wsServer"


-> websocket 모듈 설치 명령어 입력 - "npm install websocket"

(모듈을 인스톨하는 과정이 5초?정도 걸립니다)



여기까지 하셨으면 websocket 모듈은 설치가 완료되었습니다.


설치한 폴더로 가서 확인해봅시다 !



비어있던 wsServer 폴더에 node_modules \ websocket \ docs...등 하위 폴더 및 파일이 생성되신걸 확인할 수 있습니다.


자 그럼 이제 에코 서버(Echo Server)를 만들어 볼 차례입니다.



2. 에코 서버(Echo Server) 만들기


우선 서버를 만들어 봅시다 @.@



2. 1 서버(Server) - EchoServer.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 8000');
});
 
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.');
    });
});


2. 2 클라이언트(Client) - EchoClient.html


WebSocket Test Page

 



-> 서버와 클라이언트 파일을 작성하셨으면 다음과 같이 준비가 되셨습니다.




2. 3 자 그럼 작성된 에코 서버를 구동하여 줍니다.


우선 명령 프롬프트 창을 띄어줍니다.


(-> 시작(윈도우키) + R -> cmd 입력 후 엔터)


-> 작성된 에코 서버 실행 : "node EchoServer"



다음과 같이 뜨시면 성공 !



2. 4 작성된 클라이언트 페이지를 통하여 에코 테스트를 해봅시다.


Client.html 파일을 열어주시고 텍스트박스에 내용을 입력하신 후 Send 버튼 클릭.



위와 같이 서버로 전송한 내용이 되돌아와서 출력된 걸 볼 수 있습니다 .


여기까지 해서 node.js 의 websocket 모듈을 이용한 간단한 에코서버 및 클라이언트 통신 구축하기를 진행해보았습니다.


간단하지만 여기서 응용하면 멋진 프로그램을 만들 수 있을 것 같네요 ~ @.@



(+ EchoServer.js, EchoClient.html 파일을 첨부합니다)


EchoClient.html


EchoServer.js



반응형