상세 컨텐츠

본문 제목

[Node.js] Node.js를 Cloud9에서 구현하기 (socket.io를 통한 채팅 프로그램 적용)

WEB/JavaScript

by AlrepondTech 2018. 9. 30. 01:25

본문

반응형

 

 

 

=================================

=================================

=================================

 

 

 

 

 

 

 

출처: https://community.c9.io/t/writing-a-node-js-app/1731

 

 

Cloud9 IDE was built on top of the Node.js platform, and as such, you have full access to the node runtime. Currently, we support running versions v0.6.x, v0.8.x, and v0.10.x.

In this section, we’ll walk you through the creation of a simple Hello World program. To get started, you’ll first need to create a (GitHub or Mercurial) project. If you need a refresher on how to do this, please refer to Create A Workspace.

A Simple Node.js HTTP Server

Once you’re in Cloud9, create a new file called server.js. Type the following code in the file:

var http = require('http'); http.createServer(function (req, res) {     res.writeHead(200, {'Content-Type': 'text/plain'});     res.end('Hello World\n'); }).listen(process.env.PORT, process.env.IP); 

This is a Node.js HTTP server. It returns a simple “Hello World” page every time you access the page. In short, you are creating an HTTP server with a callback function that is called for each request.

In the callback function, you create a response with a status code of 200 (indicating that the request was fulfilled successfully) and the message “Hello World”. Finally, you specify which port and IP address the server runs on. When Cloud9 IDE runs servers, you set and retrieve the IP address and port number with the process.env.IP and process.env.PORT variables.

To see your application in action, click on the Run button, and the output pane will show a link created for your project. If you click on that link, you should see your “Hello World” application open up in a new preview pane. In order to access your running server from another tab, you can access it at: http://-.c9.io

NVM Support

We have rudimentary support for nvm, that allows you only to switch between Node.js versions 0.6.21 and 0.8.x.

To use nvm, open the terminal and type:

# to switch to version 0.6.21 nvm use v0.67   # to switch to the latest 0.8.x nvm use v0.8 

 

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: https://cinos81.bitbucket.io/blog/_site/javascript/2016/05/17/cloud9.html

 

 

 

 내 서버 프로그램은 Cloud9에서 작동하지 않지?

제가 생각하기로, Cloud9만큼 개발단계의 어플리케이션을 Public IP로 노출시키기 쉬운 방법도 드문 것 같습니다.
이러한 장점은 특히 모바일 웹을 개발할 때 도움이 될 것으로 보이지만, 적응하는데 약간 시간이 걸렸기에 기록해 둡니다.

일반적인 node.js서버는 이렇게 설정합니다만,

 

 

var http = require('http');http.createServer(function (req, res) {    res.writeHead(200, {'Content-Type': 'text/plain'});    res.end('Hello World\n');}).listen(3000);

 

 

이렇게 node의 환경변수를 사용하도록 변경시켜주어야만 합니다.


 

var http = require('http');http.createServer(function (req, res) {    res.writeHead(200, {'Content-Type': 'text/plain'});    res.end('Hello World\n');}).listen(process.env.PORT, process.env.IP);

 

 

출처: Writing a Node.js App On Cloud9

 

 

 

 

 

 

 

 

 

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: http://blog.naver.com/PostView.nhn?blogId=ruleoutlife&logNo=90154705703

 

 

Node.js는 서버용 언어다.

 

그런데 난 서버용 컴퓨터로 쓸 수 있는 컴퓨터가 마땅치 않다.

 

그래서 cloud9에서 제공하는 서버를 이용해 이를 해결해볼라구 한다.

 

컴터 잘하시는 분들은 이 사이트가 스크립트 편집도 쉽고 명령어 처리도 내부에서 가능하고 쏼라쏼라 각종 장점에 대해 올려놓으셨는데

 

난 그건 잘 모르겠고 아무튼 깔끔하고 좋다. 다만 속도가 느리다.

 

일단은 학습용에 적당하다고 할 수 있을 거 같다.

 

 

 

문제는 책이나 블로그에 나온 내용을 Cloud9에서 그대로 타이핑해봐야 에러만 뿜뿜한다는 것이다.

 

일단 저번에 구현했던 간단한 채팅프로그램에서 PORT 넘버와 접속 관련 부분만 일부 수정하여

 

Cloud9용으로 전환시켰다.

 

문제는 node.js는 빠른 속도로 업데이트 되고 있으므로 이 소스 코드 역시 한 일이년 지나면 다른 블로그에 올려진 코드와 마찬가지로 사용 불가하게 바뀔 가능성이 있다.

 

아무튼 지금은 먹힌다.

 

 

Cloud9의 주소는 

 

https://c9.io/

 

이다.

 

 

여기서 알아서 적당히 가입하고(없으면 알아서 가입 방법을 찾아봐야 한다. 사이트 내에 튜토리얼이 있다... 튜토리얼이란게 가입에서 계정 생성, Hellow world까지밖에 안나온게 함정)

 

로그인 후 Go to your Dashbord를 클릭한다.

 

처음엔 각종 잡다한 설명창이 뜨는데 읽고 싶으면 읽고 아니면 다 끄자.

 

 

그 후 CREATE NEW WORKSPACE라는 녹색 긴 버튼 눌러주고

 

Create a New Workspace를 선택하자

 

workspace에 이름 적당히 넣고 workspace는 Git으로 workspace privacy는 open and discoverable로 한다(이름만 넣고 그냥 엔터치면 된다. 나머진 기본 설정으로 되어 있으니...)

 

my project에 그 이름이 뜨면 이걸 클릭하고 오른편에 뜬 Start editing  녹색 버튼을 누른다.

 

 

 

그럼 본격적으로 코딩을 하면 된다.

 

먼저 만들어야 하는 파일이 두개 있다.

 

server.js와 index.html이다.

 

Cloud9에서는 서버 작동 시 server.js로부터 시작하므로 이 파일의 생성이 필수적이며 index.html은 server.js가 클라이언트로 전송해 줄 HTML 파일을 넣을 장소다

 

File을 클릭하면 New File이 뜬다.

 

이 짓을 두번 한 후

 

각각의 이름을 server.js와 index.html로 바꾼다.

 

그 다음엔 화면 제일 하단에 있는 길쭉한 콘솔창에 다음을 쳐 넣고 엔터

 

npm install express

npm install socket.io

 

 

 

그리고 다음 내용을 Ctrl C+V 해서 server.js및 index.html에 각각 넣자.

 

server.js에는

 

 

var http = require('http')

  , fs = require('fs')

  , path = require('path')

  , io = require('socket.io');

 

var server = http.createServer(function(req, res) {

  var filename = path.join(process.cwd(), req.url);

 

  path.exists(filename, function(exists) {

    if(!exists) {

      res.writeHead(404, {"Content-Type": "text/plain"});

      res.write("404 Not Found\n");

      res.end();

      return;

    }

 

    fs.readFile('./index.html', encoding='utf-8', function(err, data) {

      if (err) {

        res.writeHead(500, {"Content-Type": "text/plain"});  

        res.write(err + "\n");  

        res.end();  

        return;  

      } 

      res.writeHead(200, {"Content-Type": "text/html; charset=utf-8"}); 

      res.end(data);

    }); 

  }); 

});

 

server.listen(process.env.PORT);

 

io = io.listen(server);

 

io.configure(function(){

  io.enable('browser client etag');

  io.set('log level', 3);

  io.set('transports', [

    'websocket'

    , 'flashsocket'

    , 'htmlfile'

    , 'xhr-polling'

    , 'jsonp-polling'

    ]);

 

});

 

io.sockets.on('connection', function(socket) 

{

   console.log('connected');

   socket.on('con',function(data){

         console.log(data.text);

         socket.broadcast.emit('response',{text: data.text});                                          

                                                   });

});

console.log('서버가 시작되었습니다. http://localhost:%s',process.env.PORT);

 

 

----------------------------------------------------

 

index.html에는

 

 

<!DOCTYPE html>

<html>

  <head>

    <title>Socket.IO - Room</title>

<script type="text/javascript" src="/socket.io/socket.io.js"></script>

<script type="text/javascript">

 

var socket=io.connect();

socket.on('connect');

 

 

function $(id){return document.getElementById(id);};

 

function join(){

var tempText="";

var tempHtml="";

tempText=name_text.value+" : "+text_con.value;

tempHtml=tempText+"<BR>";

$("contents").innerHTML+=tempHtml;

$("contents").scrollTop=100000000;

socket.emit('con',{text : tempText});

$("text_con").value="";

 

 

};

 

function leave(){

$("contents").innerHTML="";

};

 

socket.on('response', function(data2){

var tempText2;

tempText2=data2.text+"<BR>";

$("contents").innerHTML+=tempText2;

$("contents").scrollTop=100000000;

});

 

</script>

  </head>

      

  <body>

    <div id="contents" style="width:300px; height:200px; overflow:auto; border:1px solid #000;">

    </div>

    <div id="content2">

     <input id="text_con"  type="text" value="" style="width:300px; height:20px; overflow:auto; 

 

border: 1px solid #000;">

    </div>

     <div>

    <input id="name_text" type="text" value="" style="width:50px; height:20px; overflow:auto; 

 

border: 1px: solid #000;">

    <input type="button" id="joinBtn" value="전송" onclick="join()"/>

    <input type="button" id="leaveBtn" value="삭제" onclick="leave()"/>

    </div>

  </body>

</html>

 

-------------------------------------------------------------

 

 

보면 알겠지만 아래에 썼던 채팅프로그램과 동일하다.

 

차이점은 채팅프로그램의 경우 개인 컴퓨터를 서버용으로 전용하여 썼기 때문에 

server.listen(3000);

 

 

으로 3000번이라는 포트를 정해서 열어줬다면

 

Cloud9에서는

server.listen(process.env.PORT);

로 변경했다는 점이다.

 

(그 외 이전에 내가 작성한 버전의 사소한 버그 하나를 수정해줬다.)

 

 

그리고 난 다음 두 개의 파일을 각각 저장시킨다.(File->Save 누르면 되고 텝에 있는 이름에 별표가 사라지면 된거임)

 

그 뒤 Run버튼을 눌러주자

 

내 소스가 가진 사소한 버그와 권장사항이 쭉 올라온다. 신경쓰지 말자

 

 

제일 첫째줄에 보면 해당 계정이 가진 서버 주소가 나온다.

 

(내 경우엔 'http:/npm.fsysy.c9.io'이다.)

 

그 주소로 들어가면 채팅프로그램이 작동하고 있음을 확인할 수 있다.

 

단 클라우드9은 서버를 제공하는 목적이 아니라 developer를 위해 만들어진 사이트로 실행한 서버는 5분정도 지나면 자동 정지되니 이 점 유의해야 한다.

 

 

 

 

 

 

 

 

 

=================================

=================================

=================================

 

 

 

기타관련링크:

 

https://opentutorials.org/course/128/11687

 

 

=================================

=================================

=================================

 

 

 

 

반응형


관련글 더보기

댓글 영역