php를 이용해서 만드는 채팅프로그램은 난이도가 있는 편이지만,
node.js로 만들게 된다면 초보자도 쉽게 따라할 수 있습니다..!!!
먼저! node.js를 다운해줍니다.(https://nodejs.org/ko)
LTS버전을 다운받겠습니다.
Node.js를 다운 받았다면 먼저 채팅프로그램을 설명하는 package.json 파일을 생성하겠습니다.
파일을 생성할 폴더는 C:\User\사용자폴더 이곳에 만들어주세요!
이유는 Node.js에서 찾기 쉬운 폴더이기 때문입니다.
package.json
1
2
3
4
5
6 |
{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {}
} |
dependencies를 다운받기위해 cmd를 열어서 npm install --save express@4.15.2 입력해줍니다.
다운이 되면 index.js 파일을 만들어줍니다.
index.js
1
2
3
4
5
6
7
8
9
10
11 |
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.send('<h1>Hello world</h1>');
});
http.listen(3000, function(){
console.log('listening on *:3000');
}); |
cs |
1.Express app은 http 서버에 제공 가능한 함수 핸들러로 초기화
2. / 웹 사이트를 방문 할 때 호출 되는 경로 처리기를 정의합니다.
3.포트 3000에서 HTTP 서버를 수신 대기하게 만듭니다.
의 기능을 담당하는 js코드입니다. 이해가 가시나요?? 안가는게 정상입니다.
cmd를 열어서 서버를 켜보죠.
node index.js를 입력해서 서버를 킵니다.
그리고 브라우저를 켜서 주소를 입력해줍니다.
자, 정리해보겠습니다.
포트번호는 3000을 이용해 접속을 했습니다.
이 문장이 포트번호를 결정하는듯 보입니다.ㅎㅎ
index.js라는 서버 파일을 만들었고, 실행해보니 hello world가 출력됬습니다.
res.send('<h1>Hello world</h1>'); 아마 이 문장 때문인것 같습니다.
이 문장을 이제 html을 실행하게 바꾸도록 합니다.
1
2
3 |
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
}); |
cs |
그리고 index.html파일을 생성합니다.
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 |
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html> |
cs |
컨트롤+c를 누르고 서버를 다시 실행시킵니다.
페이지를 새로고치면 ! 다음과 같이 표시됩니다.
Socket.IO는 두 부분으로 구성됩니다.
1. Node.JS HTTP 서버와 통합하는 서버 : socket.io
2.브라우저 측에서 로드하는 클라이언트 라이브러리 : socket.io-client
이제 모듈 하나만 더 설치하면 됩니다!
npm install --save socket.io
cmd창을 이용해서 받아줍니다.
package.json을 보면 모듈이 생긴 것을 찾을 수 있습니다.
index.js를 추가수정 하겠습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 |
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(3000, function(){
console.log('listening on *:3000');
}); |
cs |
io 기능이 추가된 것을 보실 수 있습니다.ㅎㅎ
html도 코드를 추가합니다.
</body>앞에 추가합니다.
1
2
3
4
5 |
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script> |
cs |
이제 서버와 웹사이트를 다시 로드하면 콘솔창에 'a user connected'라는 문구가 보일겁니다.
연결해제 이벤트도 소켓에서 발생되는데, 연결이 해제되었을 때 끊어졌다는 메세지를 출력해보겠습니다.
1
2
3
4
5
6 |
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
}); |
cs |
그런 다음 탭을 여러 번 새로 고침하면 반복되는 것을 볼 수 있습니다.
Socket.IO의 장점은 모든 데이터로 원하는 이벤트를 보내고 받을 수 있다는 점입니다.
사용자가 메세지를 입력 할 때 서버가 이를 chat message 이벤트로 가져 오도록하겠습니다!
index.html 스크립트 부분을 수정합니다.
1
2
3
4
5
6
7
8
9
10
11
12 |
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
</script> |
cs |
index.js 부분도 메시지를 다루도록 수정해줍니다.
1
2
3
4
5 |
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
}); |
cs |
잘 따라하셨다면 서버와 웹사이트를 다시 로드하고 메시지를 보내면 콘솔창에 아래같이 출력될겁니다.
다음은 서버에서 메시지를 보내주기 위해서 index.js의 코드를 수정하겠습니다.
1
2
3
4
5 |
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
}); |
cs |
index.html의 스크립트 코드도 수정해줍니다.
1
2
3
4
5
6
7
8
9
10
11
12
13 |
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script> |
cs |
자 완성됬씁니다!!!!!
서버를 켠다음에 http://IP:3000 or http://localhost:3000 를 이용해서 접속하면 접속한
모두와 채팅이 가능합니다!!