-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp_websocket.rb
67 lines (60 loc) · 1.77 KB
/
app_websocket.rb
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
#!/usr/bin/env ruby
# ruby examples/echochat.rb
$: << File.expand_path('../../lib/', __FILE__)
require 'sinatra'
require 'sinatra-websocket'
set :server, 'thin'
set :sockets, []
get '/' do
if !request.websocket?
erb :index
else
request.websocket do |ws|
ws.onopen do
ws.send("Hello World!")
settings.sockets << ws
end
ws.onmessage do |msg|
EM.next_tick { settings.sockets.each{|s| s.send(msg) } }
end
ws.onclose do
warn("wetbsocket closed")
settings.sockets.delete(ws)
end
end
end
end
__END__
@@ index
<html>
<body>
<h1>Simple Echo & Chat Server</h1>
<form id="form">
<input type="text" id="input" value="send a message"></input>
</form>
<div id="msgs"></div>
</body>
<script type="text/javascript">
window.onload = function(){
(function(){
var show = function(el){
return function(msg){ el.innerHTML = msg + '<br />' + el.innerHTML; }
}(document.getElementById('msgs'));
//var ws = new WebSocket('ws://' + window.location.host + window.location.pathname);
var ws = new WebSocket('ws://websockets.myhost.com:8080');
ws.onopen = function() { show('websocket opened'); };
ws.onclose = function() { show('websocket closed'); }
ws.onmessage = function(m) { show('websocket message: ' + m.data); };
var sender = function(f){
var input = document.getElementById('input');
input.onclick = function(){ input.value = "" };
f.onsubmit = function(){
ws.send(input.value);
input.value = "send a message";
return false;
}
}(document.getElementById('form'));
})();
}
</script>
</html>