¡Hola! Adjunto mi implementación de esta clase:
- src/index.js
const adminsIo = io.of('/admins');
const usersIo = io.of('/users');
adminsIo.on('connection', (socket) => {
socket.on('sendMessage', (data) => {
shareNewMessage(data, adminsIo);
});
});
usersIo.on('connection', (socket) => {
socket.on('sendMessage', (data) => {
shareNewMessage(data, usersIo);
});
});
function shareNewMessage(data, namespace) {
namespace.emit('newMessage', data);
}
- js/index.js
const user = prompt('What is your username?');
const adminUsers = ['admin', 'root'];
const isAdmin = adminUsers.includes(user);
let socketNameSpace, group;
const chatElement = document.getElementById('chat');
const namespaceElement = document.getElementById('namespace');
if (isAdmin) {
socketNameSpace = io('/admins');
group = 'admins';
} else {
socketNameSpace = io('/users');
group = 'users';
}
socketNameSpace.on('connect', () => {
namespaceElement.textContent = group.toUpperCase();
});
socketNameSpace.on('newMessage', (data) => {
receiveMessage(data);
});
function receiveMessage({ sender, message }) {
const liElement = document.createElement('li');
liElement.innerHTML += `<p><strong>${sender}</strong>: ${message}</p>`;
chatElement.appendChild(liElement);
}
function sendMessage() {
const messageElement = document.getElementById('message');
const message = messageElement.value;
if (message) {
socketNameSpace.emit('sendMessage', {
message,
sender: user,
});
}
}
- index.html
<h1>
<span id="namespace"></span>
Chat
</h1>
<ul id="chat"></ul>
<form id="chatForm" action="none">
<input type="text" id="message" placeholder="Type a message...">
<input type="button" value="Send" onclick="sendMessage()">
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="/js/index.js"></script>
¿Quieres ver más aportes, preguntas y respuestas de la comunidad?