ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Socket io
    Web/Node.js 2018. 9. 20. 11:33
    반응형

    Response와 Request가 끊이지 않게 한다.


    Client와 Server를 연결


    Push와 Pull을 할 수 있다.


    Java와 Call이랑은 다른 방식이다.


    Push는 Server가 Client한테 Data를 보내주고

    Pull은 Client가 Server한테 Data를 준다.

    Request와 REsponse가 필요없다.

    오로지 ejs와 socket만 통신한다. Router는 필요가 없어진다.

    express와 http를 연동시켜서 사용한다.


    // express와 http 연동

    -- inedx.js --

    // socket 서버 생성
    .. ~
    const socket = require("socket.io");
    const io = socket.listen(server);

    const mongo = require("./mongodb/mongo-client");
    const chat = require("./mongodb/schema/chat");

    const connectMember = [];

    // socket ==> Socket.io에 접속한 객체
    io.sockets.on('connection', (socket) => {
    // 1.접속자를 채팅방에 포함시키기
    socket.on('enter_room', (data) => {
    socket.join(data.roomName);
    io.sockets.in(data.roomName).emit('welcome', { // in을 사용하면 그 방안에서만 사용 가능
    message: '${data.me.name}님이 입장하셨습니다.'
    })

    connectMember.push({
    socketId: socket.id,
    roomName: data.roomName,
    member: data.me
    });

    chat.find({'room_name': data.roomName}, (error, results) => {
    const members = results[0].members;
    io.sockets.in(data.roomName).emit('getMemberList', {members: members});
    })

    });

    // 사용자가 채팅방을 나갔을 때 실행됨.
    // (새로고침, 브라우저 종료, 다른 url로 이동)
    socket.on('disconnect', () => {
    console.log('로그아웃');
    for ( let member of connectMember ) {
    if( member.socketId == socket.id ) {
    let roomName = member.roomName;
    let user = member.member;
    io.sockets.in(roomName) .emit('welcome', {
    message: '${user.name}님이 나가셨습니다.'
    });
    delete connectMember[member];
    chat.update({room_name: roomName}, { $pull: { members: { id: user.id } } }
    , { safe: true }
    , ( error, obj ) => {
    if ( !error ) {
    chat.find({'room_name': roomName}, (error, results) => {
    const members = results[0].members;
    io.sockets.in(roomName).emit('getMemberList', {members: members});
    })
    }
    });
    }
    }
    });
    })

    // 2.채팅 전송받고, 모두에게 전달하기
    socket.on('send', (data) => {

    chat.update({ 'room_name': data.roomName }
    , { $push: { chat: data } } );

    io.sockets.in(data.roomName).emit('receive', data);
    })


    -- chat.route.js --
    const express = require("express");
    const router = express.Router();

    const mongo = require("../mongodb/mongo-client");
    const chat = require("../mongodb/schema/chat");

    /*
    * 채팅 방 조회
    */
    router.get("/", (req, res) => {
    chat.find({}, (error, results) => {
    res.render("chat/chat", {rooms: results});
    })
    res.render("chat/chat");
    })

    router.post("/", (req, res) => {
    const room_name = req.body.room_name;
    const user = req.session.USER;

    const chatData = new chat({
    'room_name': room_name,
    members: [user],
    chat: []
    });

    chatData.save();

    res.render("chat/chat2", {
    'data': {
    'room_name': roomName,
    'me': user
    }
    });
    })

    router.get("/chat/:roomName", (req,res) => {
    const roomName = req.params.roomName;
    const user = req.session.USER;

    chat.find({'room_name': roomName}, (error, results) => {
    const oneChatRoom = new chat(results[0])
    oneChatRoom.members.push(me)
    oneCharRoom.save();

    res.render("chat/chat2", {
    'data': {
    'room_name': roomName,
    'me': me
    }
    });
    })
    });

    exports.router = router;





    -- chat2.ejs --
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="/jquery/jquery.min.js" charset="utf-8"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script type="text/javascript">
    $().ready(function() {
    // Socket에 연결하기
    const socket = io.connect();

    // emit ==> Event Call
    socket.emit('enter_room', {
    roomName: '<%=data.room_name%>',
    me: {
    id: '<%=data.me.id%>',
    name: '<%=data.me.name%>',
    point: '<%=data.me.point%>'
    }
    });

    // 누구님이 입장하셨습니다. 를 보여주기
    socket.on('welcome', (data) => {
    const welcomeMessage = $('<div>${data.message}</div>');
    $('.chat').append(welcomeMessage);
    $('.chat').scrollTop(document.querySelector('.chat').scrollHeight);
    })

    // 채팅 내용 전달받기
    socket.on('receive', (data) => {
    const chatMessage = $('<div><div class="from" data-id="${data.me.id}">${data.me.id}</div> <div class="message">${data.message}</div> </div>')
    $('.chat').append(chatMessage);
    })

    // 채팅 전송하기
    $('#chat').keydown(function(e) {
    if( e.key == 'Enter' ) {
    socket.emit('send', {
    roomName: '<%=data.room_name%>',
    me: {
    id: '<%=data.me.id%>',
    name: '<%=data.me.name%>',
    point: '<%=data.me.point%>'
    },
    message: $('#chat').val()
    })
    }
    });

    // 접속자 받아오기
    socket.on('getMemberList', (data) => {
    for ( let member of data.members ) {
    let li = $('<li data-id="${member.id}">${member.name}</li>')
    $('.members').append(li);
    }
    })
    })
    </script>
    </head>
    <body>
    <% include ../common/layout/menu %>
    <h2><%=data.room_name%></h2>
    <div class="chat">
    <div class="">
    <ul class="members">

    </ul>
    </div>
    </div>
    <div>
    <input type="hidden" id="name" name="name" value="<%=data.me.name%>" />
    <textarea name="chat" id="chat"></textarea>
    </div>
    </body>
    </html>


    -- chat.ejs --

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Chat</title>
    <script src="/jquery/jquery.min.js" charset="utf-8"></script>
    <script type="text/javascript">
    $().ready(function() {
    $('$createBtn').click(function() {
    $('createRoomForm').attr({
    action: "/chat",
    method: "post"
    }).submit();
    })
    })
    </script>
    </head>
    <body>
    <% include ../common/layout/menu %>

    <h2>입장할 방을 선택해 주세요.</h2>
    <ul>
    <% for (let room of rooms) { %>
    <li>
    <a href="/chat/<%=room.room_name%>"><%=room.room_name%> (<%room.members.length%>명)</a>
    </li>
    <% } %>
    </ul>

    <h2>새로운 방을 만드시겠습니까?</h2>
    <form id="createRoomForm">
    <input type="text" name="room_name" id="room_name" />
    <input type="button" id="createBtn" value="Create" />
    </form>
    </body>
    </html>


    -- /mongo/schema/chat.js --

    const mongoose = require('mongoose');

    const chat = mongoose.Schema({
    room_name: String
    , members: [{
    id: String
    , name: String
    , point: Number
    }]
    , chat: [{
    from: {
    id: String
    , name: String
    , point: Number
    },
    message: String
    }]
    });

    module.exports = mongoose.model("chat", chat);




    반응형

    'Web > Node.js' 카테고리의 다른 글

    package.json  (0) 2018.07.29
    서버 실행 - supervisor, forever, pm2  (0) 2018.07.23
    npm 패키지 설치시 package.json에 저장시키는 방법  (0) 2018.07.10
    node.js - var, let, const  (0) 2018.07.10
    Node.js KakaoTalk - API 2  (0) 2018.05.02

    댓글

Designed by Tistory.