-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
93 lines (85 loc) · 2.63 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
88
89
90
91
92
93
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Socket Chat</title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<style type="text/css">
dt, dd { float: left }
dt { clear:both; font-weight: bold}
dd { margin-left: 1em}
input {height: 100%}
.clickable{cursor: pointer}
body{
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr;
place-content: center;
font-family: sans-serif;
}
main{
margin: auto;
grid-column: 1 / 2;
grid-row: 1 / 2;
max-width: 650px;
width: 100%;
}
</style>
</head>
<body>
<main>
<h1 class="mt-5">Socket Chat <svg height="20" width="20"><circle id="online" cx="9" cy="9" r="8" fill="red" /></svg></h1>
<p class="lead">Esta es una web de ejemplo para probar el uso del protocolo websocket</p>
<p>
<form autocomplete="off">
<p><b>Enviar mensaje </b> <input type="text" id="msg" size="25" name="msg"> a <input type="text" id="msgTo" name="msgTo" size="4" style="text-align: center"> <span class="clickable" onclick="enviar()">enviar</span></p>
</form>
</p>
<p>A continuación aparecerán los mensajes enviados por otro canal:</p>
<dl id="chat">
</dl>
</main>
<script type="text/javascript">
var HOST = location.href.replace(/^http/, 'ws')
var msg = {};
var chat = document.getElementById("chat");
var led = document.getElementById("online");
var ws = undefined;
function enviar(){
msg.msg = document.getElementById("msg").value;
msg.to = document.getElementById("msgTo").value;
ws.send(JSON.stringify(msg));
}
function conexion() {
ws = new WebSocket(HOST);
ws.onopen = function() {
console.log('Socket is open');
led.setAttribute("fill","green")
};
ws.onmessage = function(e) {
var data = e.data;
console.log(data);
msg = JSON.parse(data);
from = document.createElement("dt");
from.innerText = msg.from + ":";
mess = document.createElement("dd");
mess.innerText = msg.msg;
chat.insertBefore(mess,chat.firstChild);
chat.insertBefore(from,chat.firstChild);
};
ws.onclose = function(e) {
led.setAttribute("fill","red")
console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
setTimeout(function() {
conexion();
}, 500);
};
ws.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket');
ws.close();
};
}
conexion();
</script>
</body>
</html>