aboutsummaryrefslogtreecommitdiff
path: root/views/client.html
blob: ebb381038818565902a24b04b1ad6b145ea94691 (plain)
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
<h2>Test client</h2>

<form>
	<label for="channelField">Channel</label>
	<input type="text" id="channelField">
	<label for="passwordField">Password (optional)</label>
	<input type="password" id="passwordField">
	<input type="checkbox" id="usePassword">
	<label for="usePassword">Use password</label>
	<input type="submit" value="Connect" id="connectButton">
</form>
<br>
<form>
	<label for="messageField">Message</label>
	<input type="text" disabled id="messageField">
	<input type="submit" value="Send" disabled id="sendButton">
</form>

<hr>
<span>Log</span>
<pre id="console"></pre>

 <script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
	var console = document.getElementById("console");

	function println(str) {
		console.innerHTML = str + "\n" + console.innerHTML;
	}

	function changeControlState(connected) {
		socketConnected = connected;
		channelField.disabled = connected;
		passwordField.disabled = connected;
		if (connected) {
			connectButton.value = "Disconnect";
		} else {
			connectButton.value = "Connect";
		}

		messageField.disabled = !connected;
		sendButton.disabled = !connected;
	}

	var socket;
	var socketConnected = false;

	function connectSocket(channel, password, authenticate) {
		socket = io.connect("/", {
			"query" : "channel=" + channel + ( authenticate ? "&password=" + password : ""),
			"force new connection" : true
		});

		socket.on("connect", function() {
			changeControlState(true);
			println("connected");
		});

		socket.on("disconnect", function() {
			changeControlState(false);
			println("disconnected");
		});

		socket.on("unknown_channel", function() {
			changeControlState(false);
			println("unknown_channel");
		});

		socket.on("authentication_error", function() {
			changeControlState(false);
			println("authentication_error");
		});

		socket.on("authenticated", function() {
			println("authenticated");
		});

		socket.on("message", function(message) {
			println(message);
		});
	}


	connectButton.addEventListener("click", function(event) {
		event.preventDefault();
		if (socketConnected) {
			socket.disconnect();
		} else {
			connectSocket(channelField.value, passwordField.value, usePassword.checked);
		}
	});

	sendButton.addEventListener("click", function(event) {
		event.preventDefault();
		socket.emit("message", messageField.value);
		messageField.value = "";
	});

</script>