-
Notifications
You must be signed in to change notification settings - Fork 32
[Node.js] WebSockets
José Bocanegra edited this page Sep 8, 2020
·
11 revisions
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;ISIS-3710 Programación con Tecnologías Web
Universidad de los Andes, Colombia