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