E. index.html

1<!DOCTYPE html>
2<html>
3
4<head>
5
6 <meta charset="UTF-8">
7 <meta name="viewport" content="width=device-width">
8
9 <title>Chat</title>
10
11 <script src="paho.javascript-1.0.3/paho-mqtt-min.js"></script>
12
13</head>
14
15<body>
16
17 <form onsubmit="formActivada(event)">
18
19 <h1>Chat</h1>
20
21 <p>
22 <label>
23 Alias *
24 <input id="inputAlias" required>
25 </label>
26 </p>
27
28 <p>
29 <label>
30 Mensaje *
31 <input id="inputMensaje" required>
32 </label>
33 </p>
34
35 <p>* Obligatorio</p>
36
37 <p><button type="submit">Enviar</button></p>
38
39 <pre id="pre"></pre>
40
41 </form>
42
43 <script type="module">
44
45 import { creaClientIdMqtt } from "./lib/js/creaClientIdMqtt.js"
46 import { falloEnLaConexionMqtt } from "./lib/js/falloEnLaConexionMqtt.js"
47 import { conexionMqttPerdida } from "./lib/js/conexionMqttPerdida.js"
48 import { muestraError } from "./lib/js/muestraError.js"
49
50 const TOPICO_CHAT = "gilpgawoas/chat"
51
52 // Cambia por una raíz para tu proyecto.
53 const clientId = creaClientIdMqtt("gilpgawoasChat-")
54
55 // Si usas un servidor de MQTT diferente, necesitas cambiar los parámetros.
56 const cliente = new Paho.MQTT.Client("test.mosquitto.org", 8081, clientId)
57
58 /**
59 * @param {Event} event
60 */
61 function formActivada(event) {
62 try {
63 event.preventDefault()
64 const mensaje = `${inputAlias.value.trim()}
65${inputMensaje.value.trim()}`
66 enviaMensajeMqtt(mensaje, TOPICO_CHAT)
67 } catch (error) {
68 muestraError(error)
69 }
70 }
71 // Permite que los eventos de html usen la función.
72 window["formActivada"] = formActivada
73
74 // Acciones al recibir un mensaje.
75 cliente.onMessageArrived = mensaje => {
76 if (mensaje.destinationName === TOPICO_CHAT) {
77 pre.textContent += mensaje.payloadString + "\n\n"
78 }
79 }
80
81 // Acciones al perder la conexión.
82 cliente.onConnectionLost = conexionMqttPerdida
83
84 // Configura el cliente.
85 cliente.connect({
86
87 keepAliveInterval: 10,
88
89 useSSL: true,
90
91 // Acciones al fallar la conexión.
92 onFailure: falloEnLaConexionMqtt,
93
94 // Acciones al lograr la conexión.
95 onSuccess: () => {
96 console.log("Conectado")
97 // Se suscribe a uno o más tópicos.
98 cliente.subscribe(TOPICO_CHAT)
99 },
100
101 })
102
103 /**
104 * Envá un valor al servidor de MQTT y es reenviado a todos los dispositivos
105 * suscritos al tópico indicado
106 * @param {string} mensaje
107 * @param {string} topico
108 */
109 function enviaMensajeMqtt(mensaje, topico) {
110 const mensajeMqtt = new Paho.MQTT.Message(mensaje)
111 mensajeMqtt.destinationName = topico
112 cliente.send(mensajeMqtt)
113 }
114
115 </script>
116
117</body>
118
119</html>
skip_previous skip_next