I am developing an exercise with socket.io where I communicate to several users depending on the room they are in, but when I write the name and save it with the id that generates socket.io By default when you change from one page to another, you lose that session and create a new one.
How can I persist that session?
The server code:
// Importando Dependencias
const express = require('express')
const path = require('path')
const SocketIO = require('socket.io')
// Usando Dependencias
const app = express()
// Configurando el servidor
app.set('port', process.env.PORT || 3000)
// Enviamos archivos estaticos al servidor
app.use(express.static(path.join(__dirname, 'public')))
// Iniciamos el servidor
const server = app.listen(app.get('port'), ()=>{
console.log('Servidor Iniciado en el puerto ${app.get('port')}')
})
// Inicializar Socket.io
const io = SocketIO(server)
// WebSockets
io.on('connect', (socket)=>{
console.log('Nueva conexion', socket.id)
// Establecemos un solo socket por room por medio de su id
let currentRoom = 'default'
socket.join(currentRoom)
// Creamos la funcion para cambiar de rooms
const moveToRoom = (newRoom)=>{
socket.leave(currentRoom)
socket.join(newRoom)
currentRoom = newRoom
socket.emit('message', {
sender:'Profesor',
content:'Has cambiado al grupo numero ${newRoom}'
})
}
socket.on('moveToRoom', moveToRoom )
// Creamos la funcion para recibir el nombre del estudiante
const onReciveStudent = (student)=>{
socket.emit('student', {
sender:socket.id,
name:student
})
console.log('Estudiante : ${student} con id ${socket.id}')
}
socket.on('student', onReciveStudent)
// Creamos la funcion para recibir mensajes
const onReciveMessage = (message)=>{
socket.to(currentRoom).emit('message',{
sender:socket.id,
content:message
})
console.log('Mensaje "${message}" desde ${socket.id} hacia la sala # ${currentRoom}')
}
socket.on('message', onReciveMessage)
// Desconectamos cualquier sesion que salga
const onDisconnect = (socket)=>{
console.log(' ${socket.id} se ha desconectado')
}
socket.on('disconnect', onDisconnect)
})
The socket code:
'use strict'
const socket = io()
// Establecemos la coneccion de lado del cliente
const onConnection = () =>{
console.log('Estudiante conectado con el id : ${socket.id}')
}
socket.on('connect',onConnection)
// Recibimos los mensajes desde el servidor
const getMessage = (message)=>{
// Agregamos el mensaje recibido al cliente web
const P = document.createElement("p")
P.appendChild(document.createTextNode('${message.sender} : ${message.content}'))
document.body.appendChild(P)
}
socket.on('message', getMessage)
// Funcion del lado del cliente para cambiar la room
const setRoom = ()=>{
socket.emit('moveToRoom', document.getElementById('room').value)
}
//Funcion para los datos del estudiante
const sendStudent = ()=>{
// Buscamos el elemento por su id y lo enviamos por medio de "emit"
const Student = document.getElementById('student')
socket.emit('student', Student.value)
window.location = './room.html'
}
// Funcion para enviar respuestas del lado del cliente
const sendMessage = ()=>{
// Buscamos el elemento por su id y lo enviamos por medio de "emit"
const Message = document.getElementById('message')
socket.emit('message', Message.value)
// Renderizamos un nuevo elemento HTML para mostrar el mensaje de lado del cliente
const P = document.createElement("p")
P.appendChild(document.createTextNode('${socket.id} : ${Message.value}'))
document.body.appendChild(P)
// Limpiamos la caja de texto despues de enviar el mensaje
Message.value=''
}