Programming/node.js2014.09.24 12:21

1. Server 예시

  1. var io = require('socket.io').listen(8001);
  2. io.sockets.on('connection', function (socket){
  3. var room_id;
  4. socket.on('joinRoom',function(data){
  5. room_id = data;
  6. socket.join(room_id); //룸입장
  7. console.log('JOIN ROOM LIST', io.sockets.adapter.rooms);
  8. });
  9. socket.on('leaveRoom',function(){
  10. socket.leave(room_id);//룸퇴장
  11. console.log('OUT ROOM LIST', io.sockets.adapter.rooms);
  12. });
  13. socket.on('sendMsg',function(data){
  14. io.sockets.in(room_id).emit('msgAlert',data);//자신포함 전체 룸안의 유저
  15. //socket.broadcast.to(room_id).emit('msgAlert',data); //자신 제외 룸안의 유저
  16. //socket.in(room_id).emit('msgAlert',data); //broadcast 동일하게 가능 자신 제외 룸안의 유저
  17. //io.of('namespace').in(room_id).emit('msgAlert', data) //of 지정된 name space의 유저의 룸
  18. });
  19. socket.on('disconnect', function(){
  20. console.log('NOT USER DISCONNECT : ', socket.id);
  21. console.log('ROOM LIST', io.sockets.adapter.rooms);
  22. });
  23. /*
  24. * 룸리스트 콘솔로그
  25. * socket.io 1.x 에서 io.sockets.manager.rooms => io.sockets.adapter.rooms
  26. * ROOM LIST { qNADgg3CCxESDLm5AAAA: [ qNADgg3CCxESDLm5AAAA: true ],
  27. test_room:
  28. [ qNADgg3CCxESDLm5AAAA: true,
  29. '0rCX3v4pufWvQ6uwAAAB': true,
  30. 'iH0wJHGh-qKPRd2RAAAC': true ],
  31. '0rCX3v4pufWvQ6uwAAAB': [ '0rCX3v4pufWvQ6uwAAAB': true ],
  32. 'iH0wJHGh-qKPRd2RAAAC': [ 'iH0wJHGh-qKPRd2RAAAC': true ] }
  33. */
  34. });


2. Client

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <title>Insert title here</title>
  6. <script src="/js/jquery-1.11.1.min.js"></script>
  7. <script src="/js/socket.io.js"></script>
  8. </head>
  9. <body>
  10. </body>
  11. <script type="text/javascript">
  12. $(function(){
  13. var socket = io.connect('http://127.0.0.1:8001', {'forceNew':true,reconnection:false});
  14. socket.on('connect', function () {
  15. socket.emit('joinRoom','test_room');
  16. socket.on('msgAlert',function(data){
  17. alert(data);
  18. });
  19. });
  20. $('#leaveRoomBut').click(function(){
  21. socket.emit('leaveRoom');
  22. });
  23. $('#msgSendBut').click(function(){
  24. socket.emit('sendMsg','TEST_MSG');
  25. });
  26. });
  27. </script>
  28. <input id="leaveRoomBut" type="button" value="leaveRoom">
  29. <input id="msgSendBut" type="button" value="msgSend">
  30. </html>


Posted by 시니^^

티스토리 툴바