티스토리 뷰



Nodejs의 socket을 이용하여 채팅구현


socket의 양방향 통신을 이용하여 채팅을 구현한다.







사전 조건


서버 환경 : CentOS, NodeJS(express+socket.io)







구성하기


먼저, 서버에는 nodejs가 설치되어있어야 한다.

작업할 폴더를 생성한 후, 아래와 같이 package.json 파일을 생성해보자


/package.json



{

  "name": "marlboroyw-chat",

  "version": "1.0.0",

  "description": "Chat P with nodejs+socket.io",

  "dependencies": {


  }

}





express 설치


아래와 같이 타이핑하여 node.js framework express 를 설치하자


[root@localhost node_chat]# npm install --save express



package.json 파일이 아래와 같이 변했을 것이다.


{

  "name": "marlboroyw-chat",

  "version": "1.0.0",

  "description": "Chat P with nodejs+socket.io",

  "dependencies": {

    "express": "^4.15.2"

  }

}


보시다시피 의존성 모듈에 express가 추가되었다.






Server Application 작성


node 서버를 돌리기 위해 아래와 같이 node_chat_server.js 를 작성해보자.



/node_chat_server.js


var app = require('express')();

var http = require('http').Server(app);


app.get('/', function(req, res){

  res.send('<h1>Hi, there</h1>');

});


http.listen(8000, function(){

  console.log('Http server started with :8000');

});







node_chat_server.js 실행


CLI 에서 아래와 같이 타이핑하여 작성했던 server를 실행시켜보자


[root@localhost node_chat]# node node_chat_server.js

Http server started with :8000


console.log 에 적었던 문자열이 CLI 상에 노출된다.

이제, localhost 의 8000번 포트로 접속해보자


http://localhost:8000



여기까지 왔다면, 

CLI 상에서 Ctrl + C 버튼을 눌러 node server 를 종료하고, 다시 코드 작성에 들어가보자.






HTML 파일 작성


다시 node_chat_server.js 를 열어 아래와 같이 바꿔주자.


/node_chat_server.js


var app = require('express')();

var http = require('http').Server(app);


app.get('/', function(req, res){

  res.sendFile(__dirname + '/index.html');

});


http.listen(8000, function(){

  console.log('Http server started with :8000');

});

 * 굵은 글씨가 수정된 부분이다.


이제 index.html 파일을 만들어보자.


/index.html


<!doctype html>


<html>

  <head>

    <title>My first socket.io chat</title>

  </head>

  <body>

<input id="sendMsg"/><button>챗고!</button>

    <ul id="msg"></ul>

  </body>

</html>


다시 노드 서버를 실행시켜 보자.


[root@localhost node_chat]# node node_chat_server.js

Http server started with :8000



http://localhost:8000 

로 접속하면 아래와 같은 화면을 볼 수 있을 것이다.


여기까진 그냥 node 연습이라고 봐도 무방할 것 같다.






Socket.io 설치하기


이제, 본격적으로 socket을 이용한 양방향 통신을 해 볼 것이다.

아래와 같이 타이핑하여 socket.io 를 설치하자.


[root@localhost node_chat]# npm install --save socket.io


package.json 이 아래와 같이 바뀐것을 확인해보자


{

  "name": "marlboroyw-chat",

  "version": "1.0.0",

  "description": "Chat P with nodejs+socket.io",

  "dependencies": {

    "express": "^4.15.2",

    "socket.io": "^1.7.3"

  }

}

socket.io 가 추가되어있다.







Socket.io 사용하기


먼저, 우리의 서버파일, node_chat_server.js 를 아래와 같이 편집해보자.


var app = require('express')();

var http = require('http').Server(app);

var io = require('socket.io')(http);


app.get('/', function(req, res){

  res.sendFile(__dirname + '/index.html');

});


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

  console.log('a user connected');

});


http.listen(8000, function(){

  console.log('Http server started with :8000');

});

굵은 글씨가 추가되었다.


프로그래머라면 딱 봐도 어떤 의미인지(nodejs 를 잘 모른다고 하더라도) 대강 알거라고 생각된다.

socket.io 모듈을 불러와, connection 메세지를 받으면, 콘솔에 로그를 찍는 내용이다.


우리의 서버파일을 고쳤으니 html 파일도 고쳐보자. 아래와같이.


<!doctype html>

<html>

  <head>

    <title>My first socket.io chat</title>

  </head>

  <body>

<input id="sendMsg"/><button>챗고!</button>

    <ul id="msg"></ul>

<script src="/socket.io/socket.io.js"></script>

<script>

var socket = io();

</script>

  </body>

</html>

* 굵은 글씨가 추가되었다.



대강 알겠는데.. /socket.io/socket.io.js 파일을 로드하는건 어떤 의미일지 궁금하다. 나는 저런 파일을 만든적이 없는데...근데..그냥 우선 해보자. 


/node_chat_server.js 파일을 실행시켜보자.


[root@localhost node_chat]# node node_chat_server.js

Http server started with :8000


평상시와 다를바 없다.

이제, 우리의 홈페이지로 접속해보자.


http://localhost:8000


마찬가지다. 다를게 없다.


이번엔 서버의 콘솔을 보자.


[root@localhost node_chat]# node node_chat_server.js

Http server started with :8000

a user connected


우리가 찍었던 로그가 찍혀있다.

소켓이 성공한것이다..!


새로고침을 몇번 해보면, 'a user connected' 로그가 계속 찍힌다. 

그렇다면 연결은 언제 disconnect 될까?


/node_chat_server.js 를 아래와 같이 고쳐보자.


var app = require('express')();

var http = require('http').Server(app);

var io = require('socket.io')(http);


app.get('/', function(req, res) {

  res.sendFile(__dirname + '/index.html');

});


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

  console.log('a user connected');

  

socket.on('disconnect', function(){

console.log('user disconnected');

});

});


http.listen(8000, function() {

  console.log('Http server started with :8000');

});


disconnect 요청을 받으면, 로그를 찍게 되는 것이다.

다시 서버를 껏다 켜서, localhost 로 들어가서 

connect 와 disconnect가 언제 발생하는지 한번 살펴보자.


(브라우저를 닫거나 새로고침하는순간 disconnect된다.)







이벤트 전송


disconnection 까지 왔다면, 다왔다.

이제 우리는 input box에 메세지를 써놓고 전송버튼을 눌러, 서버로 메세지를 던져볼 것이다.


/index.html 을 다음과 같이 수정해주자.


<!doctype html>

<html>

  <head>

    <title>My first socket.io chat</title>

  </head>

  <body>

<input id="sendMsg"/><button id="chatBtn">챗고!</button>

    <ul id="msg"></ul>

<script src="http://code.jquery.com/jquery-1.11.1.js"></script>

<script src="/socket.io/socket.io.js"></script>

<script>

var socket = io();

var chatBtn = document.querySelector('#chatBtn');

chatBtn.addEventListener("click", function(event) {

socket.emit('chat message', $('#sendMsg').val());

});

</script>

  </body>

</html>



/node_chat_server.js 를 아래와 같이 수정하자.


var app = require('express')();

var http = require('http').Server(app);

var io = require('socket.io')(http);


app.get('/', function(req, res) {

  res.sendFile(__dirname + '/index.html');

});


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

  console.log('a user connected');

  

socket.on('disconnect', function(){

console.log('user disconnected');

});

socket.on('chat message', function(msg){

console.log('msg: ' + msg);

});

});


http.listen(8000, function() {

  console.log('Http server started with :8000');

});


대강 눈치 챘겠지만, client side에서 socket 으로 'chat message' 이벤트를 보내면, 서버에서 받아서 console.log 에 출력하는 것이다.




서버를 실행시켜 결과를 보자.


[root@localhost node_chat]# node node_chat_server.js

Http server started with :8000

a user connected

여기까진 똑같다.



채팅을 작성한 후 챗고! 버튼을 눌러보자.


marlboroyw 라는 문자열을 한번 보내보자.


서버 로그를 보면 아래와 같이 로그가 찍혔다.


[root@localhost node_chat]# node node_chat_server.js

Http server started with :8000

a user connected

msg: marlboroyw


이제 정말 다 왔다.

서버 쪽에서 받아서 브로드캐스팅 형식으로 소켓에 연결되어있는 모든 사용자에게 메세지를 던져주는 일만 남았다.







브로드캐스팅


이제, 서버는 채팅 메세지를 받아서 모든 사용자에게 뿌려줄 것이다.

/node_chat_server.js 를 아래와 같이 수정하자.


var app = require('express')();

var http = require('http').Server(app);

var io = require('socket.io')(http);


app.get('/', function(req, res) {

  res.sendFile(__dirname + '/index.html');

});


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

  console.log('a user connected');

  

socket.on('disconnect', function(){

console.log('user disconnected');

});

socket.on('chat message', function(msg){

console.log('msg: ' + msg);

io.emit('chat message', msg);

});

});


http.listen(8000, function() {

  console.log('Http server started with :8000');

});

io.emit 한줄이 추가 되었다.

emit 에 대한 설명은 나중에 따로 할 예정(포스팅이 넘나 길어지는것..)


서버에서 보냈으니, client side 에서도 받아서 표시해줘야 하겠다.

client side 에서도 마찬가지로 비동기로 처리된다.


/index.html 파일을 아래와 같이 수정하자.


<!doctype html>

<html>

  <head>

    <title>My first socket.io chat</title>

  </head>

  <body>

<input id="sendMsg"/><button id="chatBtn">챗고!</button>

    <ul id="msg"></ul>

<script src="http://code.jquery.com/jquery-1.11.1.js"></script>

<script src="/socket.io/socket.io.js"></script>

<script>

var socket = io();

var chatBtn = document.querySelector('#chatBtn');

chatBtn.addEventListener("click", function(event) {

socket.emit('chat message', $('#sendMsg').val());

});

socket.on('chat message', function(msg){

$('#msg').append($('<li>').text(msg));

});

</script>

  </body>

</html>

msg id를 가진 ul 에 li 를 append 하는 것이다.


이제 서버를 다시 실행해보자.


[root@localhost node_chat]# node node_chat_server.js

Http server started with :8000

a user connected


브라우저에서 탭을 두개 열어 서로 채팅을 쳐보자..

매직..





공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함