2011-12-30 11:00:40 +00:00
|
|
|
#!/usr/bin/env ruby -I ../lib -I lib
|
2022-07-31 12:56:44 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2020-08-31 18:10:19 +00:00
|
|
|
require_relative 'rainbows'
|
2022-07-31 12:56:44 +00:00
|
|
|
|
2011-12-30 11:00:40 +00:00
|
|
|
require 'sinatra'
|
2020-08-31 18:10:19 +00:00
|
|
|
set :server, :rainbows
|
2011-12-30 11:00:40 +00:00
|
|
|
connections = []
|
|
|
|
|
|
|
|
get '/' do
|
|
|
|
halt erb(:login) unless params[:user]
|
2022-07-31 12:56:44 +00:00
|
|
|
erb :chat, locals: { user: params[:user].gsub(/\W/, '') }
|
2011-12-30 11:00:40 +00:00
|
|
|
end
|
|
|
|
|
2022-07-31 12:56:44 +00:00
|
|
|
get '/stream', provides: 'text/event-stream' do
|
2011-12-30 11:00:40 +00:00
|
|
|
stream :keep_open do |out|
|
|
|
|
connections << out
|
|
|
|
out.callback { connections.delete(out) }
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
post '/' do
|
|
|
|
connections.each { |out| out << "data: #{params[:msg]}\n\n" }
|
|
|
|
204 # response without entity body
|
|
|
|
end
|
|
|
|
|
|
|
|
__END__
|
|
|
|
|
|
|
|
@@ layout
|
|
|
|
<html>
|
2012-07-18 19:07:24 +00:00
|
|
|
<head>
|
|
|
|
<title>Super Simple Chat with Sinatra</title>
|
2011-12-30 11:00:40 +00:00
|
|
|
<meta charset="utf-8" />
|
2012-07-18 19:07:24 +00:00
|
|
|
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
|
|
|
|
</head>
|
2011-12-30 11:00:40 +00:00
|
|
|
<body><%= yield %></body>
|
|
|
|
</html>
|
|
|
|
|
|
|
|
@@ login
|
|
|
|
<form action='/'>
|
|
|
|
<label for='user'>User Name:</label>
|
|
|
|
<input name='user' value='' />
|
|
|
|
<input type='submit' value="GO!" />
|
|
|
|
</form>
|
|
|
|
|
|
|
|
@@ chat
|
|
|
|
<pre id='chat'></pre>
|
2013-03-08 01:56:53 +00:00
|
|
|
<form>
|
|
|
|
<input id='msg' placeholder='type message here...' />
|
|
|
|
</form>
|
2011-12-30 11:00:40 +00:00
|
|
|
|
|
|
|
<script>
|
|
|
|
// reading
|
|
|
|
var es = new EventSource('/stream');
|
|
|
|
es.onmessage = function(e) { $('#chat').append(e.data + "\n") };
|
|
|
|
|
|
|
|
// writing
|
2013-02-19 07:42:31 +00:00
|
|
|
$("form").on('submit',function(e) {
|
2011-12-30 11:00:40 +00:00
|
|
|
$.post('/', {msg: "<%= user %>: " + $('#msg').val()});
|
|
|
|
$('#msg').val(''); $('#msg').focus();
|
|
|
|
e.preventDefault();
|
|
|
|
});
|
|
|
|
</script>
|
|
|
|
|