1. Server 예시
- var io = require('socket.io').listen(8001);
- io.sockets.on('connection', function (socket){
- var room_id;
- socket.on('joinRoom',function(data){
- room_id = data;
- socket.join(room_id); //룸입장
- console.log('JOIN ROOM LIST', io.sockets.adapter.rooms);
- });
- socket.on('leaveRoom',function(){
- socket.leave(room_id);//룸퇴장
- console.log('OUT ROOM LIST', io.sockets.adapter.rooms);
- });
- socket.on('sendMsg',function(data){
- io.sockets.in(room_id).emit('msgAlert',data);//자신포함 전체 룸안의 유저
- //socket.broadcast.to(room_id).emit('msgAlert',data); //자신 제외 룸안의 유저
- //socket.in(room_id).emit('msgAlert',data); //broadcast 동일하게 가능 자신 제외 룸안의 유저
- //io.of('namespace').in(room_id).emit('msgAlert', data) //of 지정된 name space의 유저의 룸
- });
- socket.on('disconnect', function(){
- console.log('NOT USER DISCONNECT : ', socket.id);
- console.log('ROOM LIST', io.sockets.adapter.rooms);
- });
- /*
- * 룸리스트 콘솔로그
- * socket.io 1.x 에서 io.sockets.manager.rooms => io.sockets.adapter.rooms
- * ROOM LIST { qNADgg3CCxESDLm5AAAA: [ qNADgg3CCxESDLm5AAAA: true ],
- test_room:
- [ qNADgg3CCxESDLm5AAAA: true,
- '0rCX3v4pufWvQ6uwAAAB': true,
- 'iH0wJHGh-qKPRd2RAAAC': true ],
- '0rCX3v4pufWvQ6uwAAAB': [ '0rCX3v4pufWvQ6uwAAAB': true ],
- 'iH0wJHGh-qKPRd2RAAAC': [ 'iH0wJHGh-qKPRd2RAAAC': true ] }
- */
- });
2. Client
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- <script src="/js/jquery-1.11.1.min.js"></script>
- <script src="/js/socket.io.js"></script>
- </head>
- <body>
- </body>
- <script type="text/javascript">
- $(function(){
- var socket = io.connect('http://127.0.0.1:8001', {'forceNew':true,reconnection:false});
- socket.on('connect', function () {
- socket.emit('joinRoom','test_room');
- socket.on('msgAlert',function(data){
- alert(data);
- });
- });
- $('#leaveRoomBut').click(function(){
- socket.emit('leaveRoom');
- });
- $('#msgSendBut').click(function(){
- socket.emit('sendMsg','TEST_MSG');
- });
- });
- </script>
- <input id="leaveRoomBut" type="button" value="leaveRoom">
- <input id="msgSendBut" type="button" value="msgSend">
- </html>