-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
87 lines (73 loc) · 2.69 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Go WebSocket Tutorial</title>
</head>
<body>
<h1>Cliente de Chat en GO</h1>
<div>
<input type="text" id="username">
<button id="connect">Conectar</button>
</div>
<form id="chat-form">
<input type="text" name="target" placeholder="ingrese el usuario destino">
<input type="text" name="message" placeholder="ingrese el mensaje">
<button>Enviar</button>
</form>
<br>
<div>
<h2>Mensajes: </h2>
<ul id="lista"></ul>
</div>
<script>
let username="";
let conButton = document.getElementById('connect');
let inputUsername = document.getElementById('username');
let formulario = document.getElementById('chat-form');
//let lista = document.getElementById('lista');
let socket;
conButton?.addEventListener('click', () => {
username = inputUsername?.value;
socket = new WebSocket(`ws://127.0.0.1:8000/chat?username=${username}`);
socket.addEventListener('message', event => {
//console.log('<--', JSON.parse(event.data));
const data = JSON.parse(event.data);
AgregarMensaje('<-- ' + data.sender + ': ' + data.body);
});
socket.onopen = event => {
console.log('Conectado');
};
socket.onclose = event => {
console.log("Desconectado: ", event);
//socket.send("Desconectado!")
};
socket.onerror = error => {
console.log("Error de conexión: ", error);
};
});
formulario?.addEventListener('submit', event => {
event.preventDefault(); // para que no recargue la página
const data = {
sender: username,
target: formulario.target.value,
body: formulario.message.value,
};
socket.send(JSON.stringify(data));
//console.log("-->",data);
AgregarMensaje('--> ' + data.target + ': ' + data.body);
});
function AgregarMensaje( $msg ) {
var li = document.createElement("li");
//var p = document.createElement("p");
//p.appendChild(document.createTextNode($msg));
li.appendChild(document.createTextNode($msg));
document.querySelector("#lista").appendChild(li);
//lista.appendChild(li).appendChild(p);
//document.querySelector("#lista").appendChild(li).appendChild(p);
}
</script>
</body>
</html>