blob: aadf2b24a86c0241a1463eaea5e25843e6b1bae2 (
plain) (
blame)
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Websocket client</title>
</head>
<body>
<header>
<h1>Websocket client</h1>
<div id="status"></div>
</header>
<nav>
<div id="connecting">
<input type='text' id="server" value=""></input>
<button type="button" onclick="toggle_connection()">connection</button>
</div>
<div id="connected">
<input type='text' id="message" value=""></input>
<button type="button" onclick="sendTxt();">send</button>
</div>
</nav>
<main id="content">
<button id="clear" onclick="clearScreen()" >Clear text</button>
<div id="output"></div>
</main>
<script type="text/javascript">
var websocket;
var server = document.getElementById("server");
var message = document.getElementById("message");
var connecting = document.getElementById("connecting");
var connected = document.getElementById("connected");
var content = document.getElementById("content");
var output = document.getElementById("output");
server.value = "ws://" + window.location.host + "/websocket";
connected.style.display = "none";
content.style.display = "none";
function connect()
{
wsHost = server.value;
websocket = new WebSocket(wsHost);
showScreen('<b>Connecting to: ' + wsHost + '</b>');
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
};
function disconnect() {
websocket.close();
};
function toggle_connection(){
if (websocket && websocket.readyState == websocket.OPEN) {
disconnect();
} else {
connect();
};
};
function sendTxt() {
if (websocket.readyState == websocket.OPEN) {
var msg = message.value;
websocket.send(msg);
showScreen('sending: ' + msg);
} else {
showScreen('websocket is not connected');
};
};
function onOpen(evt) {
showScreen('<span style="color: green;">CONNECTED </span>');
connecting.style.display = "none";
connected.style.display = "";
content.style.display = "";
};
function onClose(evt) {
showScreen('<span style="color: red;">DISCONNECTED</span>');
};
function onMessage(evt) {
showScreen('<span style="color: blue;">RESPONSE: ' + evt.data + '</span>');
};
function onError(evt) {
showScreen('<span style="color: red;">ERROR: ' + evt.data + '</span>');
};
function showScreen(html) {
var el = document.createElement("p");
el.innerHTML = html;
output.insertBefore(el, output.firstChild);
};
function clearScreen() {
output.innerHTML = "";
};
</script>
</body>
</html>
|