| 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 type="module" src="js/lib/manejaErrores.js"></script> |
| 12 | <script src="paho.javascript-1.0.3/paho-mqtt-min.js"></script> |
| 13 | |
| 14 | </head> |
| 15 | |
| 16 | <body> |
| 17 | |
| 18 | <form id="formulario"> |
| 19 | |
| 20 | <h1>Chat</h1> |
| 21 | |
| 22 | <p> |
| 23 | <label> |
| 24 | Alias * |
| 25 | <input id="inputAlias" required> |
| 26 | </label> |
| 27 | </p> |
| 28 | |
| 29 | <p> |
| 30 | <label> |
| 31 | Mensaje * |
| 32 | <input id="inputMensaje" required> |
| 33 | </label> |
| 34 | </p> |
| 35 | |
| 36 | <p>* Obligatorio</p> |
| 37 | |
| 38 | <p><button type="submit">Enviar</button></p> |
| 39 | |
| 40 | <pre id="pre">Conectando…</pre> |
| 41 | |
| 42 | </form> |
| 43 | |
| 44 | <script type="module"> |
| 45 | |
| 46 | import { creaIdCliente } from "./js/lib/creaIdCliente.js" |
| 47 | import { falloEnLaConexionMqtt } from "./js/lib/falloEnLaConexionMqtt.js" |
| 48 | import { conexionMqttPerdida } from "./js/lib/conexionMqttPerdida.js" |
| 49 | import { enviaMensajeMqtt } from "./js/lib/enviaMensajeMqtt.js" |
| 50 | |
| 51 | const TOPICO_CHAT = "gilpgawoas/chat" |
| 52 | |
| 53 | |
| 54 | const clientId = creaIdCliente("gilpgawoasChat-") |
| 55 | |
| 56 | |
| 57 | const cliente = new Paho.MQTT.Client("test.mosquitto.org", 8081, clientId) |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | function submit(event) { |
| 63 | event.preventDefault() |
| 64 | const mensaje = `${inputAlias.value.trim()} |
| 65 | ${inputMensaje.value.trim()}` |
| 66 | enviaMensajeMqtt(cliente, mensaje, TOPICO_CHAT) |
| 67 | } |
| 68 | |
| 69 | |
| 70 | cliente.onMessageArrived = mensaje => { |
| 71 | if (mensaje.destinationName === TOPICO_CHAT) { |
| 72 | pre.textContent += mensaje.payloadString + "\n\n" |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | |
| 77 | cliente.onConnectionLost = conexionMqttPerdida |
| 78 | |
| 79 | |
| 80 | cliente.connect({ |
| 81 | |
| 82 | |
| 83 | |
| 84 | keepAliveInterval: 10, |
| 85 | |
| 86 | useSSL: true, |
| 87 | |
| 88 | |
| 89 | onFailure: falloEnLaConexionMqtt, |
| 90 | |
| 91 | |
| 92 | onSuccess: () => { |
| 93 | console.log("Conectado.") |
| 94 | pre.textContent = "Conectado.\n\n" |
| 95 | |
| 96 | cliente.subscribe(TOPICO_CHAT) |
| 97 | formulario.addEventListener("submit", submit) |
| 98 | }, |
| 99 | |
| 100 | }) |
| 101 | |
| 102 | </script> |
| 103 | |
| 104 | </body> |
| 105 | |
| 106 | </html> |