# finish with `exit` if running within `irb`
require 'plezi'
class ChatServer
def index
render 'client'
end
def on_open
return close unless params['id']
@name = params['id']
subscribe "chat"
publish "chat", "#{@name} joind the chat."
write "Welcome, #{@name}!"
end
def on_close
publish "chat", "#{@name} joind the chat."
end
def on_message data
publish "chat", "#{@name}: #{data}"
end
end
# setup route to html/javascript client
path_to_client = File.expand_path( File.dirname(__FILE__) )
Plezi.templates = path_to_client
# connect route to controller
Plezi.route '/', ChatServer
<!-- client.html.erb -->
<!DOCTYPE html><html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
ws = NaN
handle = ''
function onsubmit(e) {
e.preventDefault();
if($('#text')[0].value == '') {return false}
if(ws && ws.readyState == 1) {
ws.send($('#text')[0].value);
$('#text')[0].value = '';
} else {
handle = $('#text')[0].value
var url = (window.location.protocol.match(/https/) ? 'wss' : 'ws') +
'://' + window.document.location.host +
'/' + $('#text')[0].value
ws = new WebSocket(url)
ws.onopen = function(e) {
output("<b>Connected :-)</b>");
$('#text')[0].value = '';
$('#text')[0].placeholder = 'your message';
}
ws.onclose = function(e) {
output("<b>Disonnected :-/</b>")
$('#text')[0].value = '';
$('#text')[0].placeholder = 'nickname';
$('#text')[0].value = handle
}
ws.onmessage = function(e) {
output(e.data);
}
}
return false;
}
function output(data) {
$('#output').append("<li>" + data + "</li>")
$('#output').animate({ scrollTop:
$('#output')[0].scrollHeight }, "slow");
}
</script>
</head><body>
<form id='form'>
<input type='text' id='text' name='text' placeholder='nickname'></input>
<input type='submit' value='send'></input>
</form>
<script> $('#form')[0].onsubmit = onsubmit </script>
<ul id='output'></ul>
</body>