F. 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 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
  // Cambia por una raíz para tu proyecto.
54
  const clientId = creaIdCliente("gilpgawoasChat-")
55
56
  // Si usas un servidor de MQTT diferente, necesitas cambiar los parámetros.
57
  const cliente = new Paho.MQTT.Client("test.mosquitto.org", 8081, clientId)
58
59
  /**
60
   * @param {Event} event
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
  // Acciones al recibir un mensaje.
70
  cliente.onMessageArrived = mensaje => {
71
   if (mensaje.destinationName === TOPICO_CHAT) {
72
    pre.textContent += mensaje.payloadString + "\n\n"
73
   }
74
  }
75
76
  // Acciones al perder la conexión.
77
  cliente.onConnectionLost = conexionMqttPerdida
78
79
  // Configura el cliente.
80
  cliente.connect({
81
82
   // Manda un mensaje cada número de segundos indicados por este valor,
83
   // para que el sistema sepa que este dispositivo está activo.
84
   keepAliveInterval: 10,
85
86
   useSSL: true,
87
88
   // Acciones al fallar la conexión.
89
   onFailure: falloEnLaConexionMqtt,
90
91
   // Acciones al lograr la conexión.
92
   onSuccess: () => {
93
    console.log("Conectado.")
94
    pre.textContent = "Conectado.\n\n"
95
    // Se suscribe a uno o más tópicos.
96
    cliente.subscribe(TOPICO_CHAT)
97
    formulario.addEventListener("submit", submit)
98
   },
99
100
  })
101
102
 </script>
103
104
</body>
105
106
</html>
skip_previous skip_next