Tutorial del Internet de las Cosas y Bluetooth con el ESP32
Juan Antonio Villalpando
Volver al índice del tutorial
____________________________
117.- Node.js y Chat.
- https://allfront.io/blog/building-a-node-js-chat-with-socket-io
- Instalamos express
npn install express
- Instalamos socket.io
npn install socket.io

- Obtengo errores ya que la versión de node que he instalado es la v8.17.0 para Windows 7 y la versión de io.socket es más reciente, así que voy a instalar una versión de socket.io más vieja:
npm install socket.io@2.4.0

- Dentro de la carpeta donde tenemos el node.exe vamos a crear otra carpeta llamada socketschat

- Dentro de esa carpeta crearemos un archivo llamado package.json con este contenido:
package.json |
{
"name": "socketschat",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"socket.io": "^2.0.4"
}
}
|
- Otro archivo llamado server.js con este contenido:
server.js |
const application = require('express')();
const server = require('http').createServer(application)
const io = require('socket.io')(server);
const PORT = process.env.PORT || 3000
application.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
server.listen(PORT, () => {
console.log('Server is running on port: ' + PORT);
});
io.on('connection', (socket) => {
socket.on('disconnect', () => {
console.log('User disconnected - Username: ' + socket.username);
});
socket.on('new message', (msg) => {
io.emit('send message', {message: msg, user: socket.username});
});
socket.on('new user', (usr) => {
socket.username = usr;
console.log('User connected - Username: ' + socket.username);
});
});
|
- Y otro archivo llamado index.html con este contenido:
index.html |
<!DOCTYPE html>
<html>
<head>
<title>SocketsChat</title>
<script src="/socket.io/socket.io.js"></script>
<link rel="stylesheet" href="index.css">
</head>
<body>
<ul id="message_list"></ul>
<form id="message_area" action="">
<input id="text_area" autocomplete="off" />
<button>Send</button>
</form>
<script>
const socket = io();
const username = window.prompt("Enter the username");
socket.emit('new user', username);
const messageForm = document.getElementById('message_area');
const textInput = document.getElementById('text_area');
messageForm.addEventListener('submit', function(e) {
e.preventDefault();
if (textInput.value) {socket.emit('new message', textInput.value);
textInput.value = '';
}
});
socket.on('send message', (data) => {
const messageList = document.getElementById('message_list');
const chatItem = document.createElement('li');
chatItem.textContent = data.user + ': ' + data.message;
messageList.appendChild(chatItem);
window.scrollTo(0, document.body.scrollHeight);
});
</script>
</body>
</html>
|
- Observa cómo arrancamos el servidor.
- Estando en el directorio D:\Downloads\node-v8.17.0-win-x64\node-v8.17.0-win-x64\socketschat
escribimos:
..\node server.js

- Ahora vamos a un navegador, escribimos la IP del servidor, en mi caso 192.168.1.40
- Abrimos otra pestaña del navegador, y escribimos la misma dirección, 192.168.1.40:3000
- Ponemos nuestro nombre y chatearemos con el usuario anterior.
____________________________________________
2.- Chat.
p340Bi_nodejs_chat.aia
- Esta app simplemente envía información al servidor y la vuelve a recibir, no es exactamente un chat, además es lento, tarda unos segundos en responder.
- Cambiamos el archivo index.html
index.html |
<!DOCTYPE html>
<html><head>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
const socket = io();
var username = window.AppInventor.getWebViewString();
if(username.startsWith("me:")){
socket.emit('new user', username);
} else {
socket.emit('new message', username);
socket.on('send message', (data) => {
window.AppInventor.setWebViewString("" + data.message);
});
}
</script>
</body></html>
|
____________________________________________
- Diseño.

____________________________________________
- Bloques.

_______________________________
|