forked from ghedipunk/PHP-Websockets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clientwithprotocol.html
109 lines (103 loc) · 2.38 KB
/
clientwithprotocol.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<html><head><title>WebSocket</title>
<style type="text/css">
html,body {
font:normal 0.9em arial,helvetica;
}
#log {
width:600px;
height:300px;
border:1px solid #7F9DB9;
overflow:auto;
}
#msg {
width:400px;
}
</style>
<script type="text/javascript">
var ws;
function init() {
var host = "ws://127.0.0.1:9000/echobot"; // SET THIS TO YOUR SERVER host:port/ressource
try {
// Using protocol is NOT MANDATORY you can safely remove it completely.
// If you use protocol the server MUST choose ONLY ONE protocol.
// ws.protocol store the protocol the server choose
// use it in both direction ( receiving and sending )
var proto=['invalidprotocol','broadcasting','echobot','json','msgpack'];
ws = new WebSocket(host,proto); // (host,protocol) protocol placed in order of priority
log('WebSocket - status '+ws.readyState);
ws.onopen = function(msg) {
log("Welcome - status "+this.readyState);
if (ws.protocol)
{
log(">using protocol; "+ws.protocol);
}
};
ws.onmessage = function(msg) {
var protocol="no";
switch (ws.protocol) {
case 'json' : protocol="json";
break;
case 'msgpack' : protocol="msgpack";
break;
case 'echobot' : protocol="echobot";
break;
case 'broadcasting' : protocol="broadcasting";
}
log(protocol+" protocol Received: "+msg.data);
};
ws.onerror = function(msg) {
console.log(msg); //helpfull for debugging
};
ws.onclose = function(msg) {
console.log(msg);
log("Disconnected - status "+this.readyState);
};
}
catch(ex){
log(ex);
}
$("msg").focus();
}
function send(){
var txt,msg;
txt = $("msg");
msg = txt.value;
if(!msg) {
alert("Message can not be empty");
return;
}
txt.value="";
txt.focus();
try {
ws.send(msg);
log('Sent: '+msg);
} catch(ex) {
log(ex);
}
}
function quit(){
if (ws != null) {
log("Goodbye!");
ws.close();
ws=null;
}
}
function reconnect() {
quit();
init();
}
// Utilities
function $(id){ return document.getElementById(id); }
function log(msg){ $("log").innerHTML+="<br>"+msg; }
function onkey(event){ if(event.keyCode==13){ send(); } }
</script>
</head>
<body onload="init()">
<h3>WebSocket v2.00</h3>
<div id="log"></div>
<input id="msg" type="textbox" onkeypress="onkey(event)"/>
<button onclick="send()">Send</button>
<button onclick="quit()">Quit</button>
<button onclick="reconnect()">Reconnect</button>
</body>
</html>