2018. 4. 22. 22:43
반응형

예전에 블로그에 채팅창을 달 때 가가라이브 채팅창을 이용했었다.

최근에 채팅창 구현에 관해 알아보다가 pubnub라는 사이트를 알게 되었다.

사용량이나 채팅참여자가 매우 많지 않다면 무료로 이용하는 것도 괜찮아보인다.

채팅창 디자인이나 세부 기능 같은 부분을 자신이 원하는대로 커스터마이징 가능하다.


https://www.pubnub.com 에 가입하고 키를 발급받아 이용하면 된다.

참고할만한 문서 https://www.pubnub.com/docs/web-javascript/pubnub-javascript-sdk


pubnub.history 기능을 이용해서 채팅창이 로딩되면 최근 대화를 불러오도록 했다.

아래 코드를 그대로 복사해서 붙여넣으면 대충 기능은 잘 작동할 것이다.

검색을 하여 잘 찾아보면 jquery mobile을 이용하여 디자인이 잘 된 pubnub 채팅창 소스도 있었던 것 같다.




<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.pubnub.com/pubnub-3.4.4.js"></script> <script> var pubnub = PUBNUB.init({ publish_key: 'pub-c-5420be45-0fb1-47f9-8ea6-13b4c0c4a37e', subscribe_key: 'sub-c-99fff064-4631-11e8-afae-2a65d00afee8', ssl: true }); pubnub.subscribe({ channel: 'chat', message: displayPub }); pubnub.history({ channel: 'chat', reverse: true, count: 100 }, function(status, response){ $.each(status[0], function(i, item){ displayPub(item); }); }); function displayPub(message){ var html = "<div>"+message.username+": "+message.text+"</div>"; $("#chatPub").append(html).scrollTop(999999); } function sendPub(){ if($("#name").val() == ''){ alert("enter your name"); return; } if($("#messagePub").val() == '') return; pubnub.publish({ channel: 'chat', message:{ username: $("#name").val(), text: $("#messagePub").val() } }); $("#messagePub").val('').focus(); } $(document).ready(function(){ $("#sendPub").click(function(){ sendPub(); }); $("#messagePub").keyup(function(event){ if(event.keyCode == 13) sendPub(); }); }); </script> <input type="text" id="name" placeholder="name" required/> <input type="text" id="messagePub" placeholder="message" required/> <input type="submit" id="sendPub" value="enter"/> <div id="chatPub" style="overflow: auto;height:200px;"></div>



반응형