socket io connection 이벤트가 여러번 발생합니다.
module.exports = function (app, fs, connection, io) { var users = [] ; app.get('/', function (req, res) { res.render('index'); }); app.get('/lobby', function (req, res) { res.render('lobby', { id: req.session.user_id }); var lobbyManager = require('./lobbyManager')(io, users, req.session); }); ... }
로그인에 성공했을시 라우터에서 대기실 화면으로 보내주는 코드입니다.
module.exports = function (io, users, session) { io.sockets.on('connection', function (socket) { console.log('connection event'); socket.emit('getType'); console.log('getType event'); socket.on('sendType', function (type) { console.log('sendType event'); if (users[session.user_id]) { users[session.user_id][type] = socket.id; } else { var user = {}; user[type] = socket.id; users[session.user_id] = user; } console.log(users); }); }); }
이것이 대기실을 관리하는 코드인데요 두명의 유저를 접속 시켰을때
client_on > login : {"id":"test","password":"test"}
session add : "test"
connection event
getType event
sendType event
[ test: { clientSocketID: '/#cqXaOF9TwXccRR-8AAAC' } ]
client_on > login : {"id":"admin","password":"admin"}
session add : "admin"
connection event
getType event
connection event
getType event
sendType event
[ test: { clientSocketID: '/#6xns90HBO2_oZPoDAAAD' } ]
sendType event
[ test: { clientSocketID: '/#6xns90HBO2_oZPoDAAAD' },
admin: { clientSocketID: '/#6xns90HBO2_oZPoDAAAD' } ]
sendType event
[ test: { clientSocketID: '/#6xns90HBO2_oZPoDAAAD' },
admin: { clientSocketID: '/#6xns90HBO2_oZPoDAAAD' } ]
sendType event
[ test: { clientSocketID: '/#6xns90HBO2_oZPoDAAAD' },
admin: { clientSocketID: '/#6xns90HBO2_oZPoDAAAD' } ]
위와 같이 첫번째 로그인은 users배열에 user가 등록이 잘 되고
두번째 유저가 로그인 할 때 connection 이벤트가 두번이나 발생하게 되고 그 이후의 이벤트들도 여러번 발생합니다. 그러면서 덮어 씌워저 버립니다.
가장 궁금한것은 connection 이벤트가 왜 두번이나 발생하는지
그리고 users배열에 데이터들이 왜 덮어 씌워지는지 입니다.
원인이나 해결법 혹은 참조할만한 것이라도 꼭 알려주세요 ㅠㅠ
참고로 클라이언트의 코드는 아래와 같습니다.
var socket = io(); socket.on('getType', function(){ socket.emit('sendType', "clientSocketID"); });
1회차 connecgtion event 리스너 호출
1회차
connecgtion event 리스너 호출 1회
getType event 리스너 호출 1회
sendType event 리스너 호출 1회
2회차
connection event 리스너 호출 2회
getType event 리스너 호출 2회
sendType event 리스너 호출 4회
그리고 socket.id가 모두 동일
결과를 보니 이벤트 리스너가 중복으로 등록되고 있는 상황이 아닌가 의심됩니다.
댓글 달기