본문 바로가기
프로그래밍/node.js

(Node.js 예제) 접속할 때마다 count 하기

by LiveData 2018. 12. 4.
반응형

Count 예제



사이트를 들어갈 때마다 count를 띄워



1씩 올라가는 예제를 해보겠습니다.




index.html


1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1 id="users-count">?</h1>
<script src="/socket.io/socket.io.js"></script>
<script>
    var socket=io('http://localhost:5000');
    socket.on('users.count'function(number) {
        document.getElementById('users-count').innerHTML=number;
    });
</script>
</body>
</html>
cs



socket의 변수를 생성하고


socket.on으로 이벤트가 들어오면 즉각적으로 바뀔 수 있게 합니다.


변수가 들어오는 function(number)의 number가 count부분이 됩니다.


document.getElementById('users-count').innerHTML=number;


는 html 문법으로 id='users-count'를 찾아서 number 변수로 교체합니다.




server.js


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
 
var express=require('express'),
    app=express(),
    http=require('http'),
    socketIO=require('socket.io'),
    server, io;
 
 
app.get('/'function(req,res) {
    res.sendFile(__dirname+'/index.html');
});
 
server=http.Server(app);
server.listen(5000);
 
io=socketIO(server);
 
var count=0;
 
io.on('connection'function(socket){
    count++;
    io.emit('users.count',count);
    socket.on('disconnect',function() {
        count--;
        io.emit('users.count',count);
    });
});
cs




변수로 소켓과 express들을 선언하고


app.get은 get으로 요청이 들어오면 


index.html을 불러옵니다. (바로 index.html을 띄우게 되죠)


server.listen(5000);
 
io=socketIO(server); // 소켓 포트를 5000으로 하고 소켓을 생성합니다.




io.on('connection'function(socket){
    count++; //사용자가 들어오면 count를 1늘린다.
    io.emit('users.count',count); // 접속해있는 모든 사용자의 users.count되있는 부분에 count변수를 뿌림.
    socket.on('disconnect',function() { //접속해있는 연결이 종료될 경우 count--해준다.
        count--;
        io.emit('users.count',count); //빼준 count를 접속해있는 모든 user에게 뿌림.
    });
});




결   과


안보이지만 3개가 켜져있습니다.







역시 node.js+socket.io의 가장 강점!


실시간.


직접 해보니 어썸합니다..

반응형