Refactor code for socket.io