-
Notifications
You must be signed in to change notification settings - Fork 32
[Node.js] WebSockets
En este ejercio se construirá un chat usando el concepto de WebSockets para establecer comunicación bidireccional entre cliente y servidor.
Cree un nuevo proyecto de express express --no-view --git chat
Instale la librería ws: npm install ws -save.
En la raiz cree un nuevo archivo wslib.js con el siguiente código:
const WebSocket = require("ws");
const clients = [];
const messages = [];
const wsConnection = (server) => {
const wss = new WebSocket.Server({ server });
wss.on("connection", (ws) => {
clients.push(ws);
ws.on("message", (message) => {
messages.push(message);
clients.forEach((ws) => ws.send(JSON.stringify(messages)));
});
});
};
exports.wsConnection = wsConnection;Modifique el archivo bin/www y agregue la referencia al nuevo archivo creado:
let ws = require("../wslib");
En ese mismo archivo, después de haber definido el servidor, inlcuya esta nueva línea:
var server = http.createServer(app);
ws.wsConnection(server);
Modifique el archivo public/index.html así:
<html>
<head>
<title>Express</title>
<link rel="stylesheet" href="/stylesheets/style.css" />
</head>
<body>
<h1>Chat</h1>
<div id="messages"></div>
<form id="form">
<input type="text" id="message" />
<input type="submit" value="submit" />
</form>
<script src="./javascripts/app.js"></script>
</body>
</html>Cree un nuevo archivo public/javasripts/app.js con el siguiente contenido:
ws = new WebSocket("ws://localhost:3000");
this.ws.onmessage = (msg) => {
render(JSON.parse(msg.data));
};
let render = (data) => {
let html = data.map((item) => `<p>${item}</p>`).join(" ");
document.getElementById("messages").innerHTML = html;
};
let handleSubmit = (evt) => {
evt.preventDefault();
let message = document.getElementById("message");
ws.send(message.value);
message.value = "";
};
let form = document.getElementById("form");
form.addEventListener("submit", handleSubmit);Desde una consola, ejecute npm start. Abra en dos navegadores la URL http://localhost:3000/.
Verifique que al enviar un mensaje al chat este se propaga a la otra ventana del navegador.
ISIS-3710 Programación con Tecnologías Web
Universidad de los Andes, Colombia