Skip to content
This repository
Newer
Older
100755 61 lines (51 sloc) 1.33 kb
88406916 » rkh
2011-12-30 add examples directory
1 #!/usr/bin/env ruby -I ../lib -I lib
2 # coding: utf-8
3 require 'sinatra'
4 set :server, 'thin'
5 connections = []
6
7 get '/' do
8 halt erb(:login) unless params[:user]
9 erb :chat, :locals => { :user => params[:user].gsub(/\W/, '') }
10 end
11
12 get '/stream', :provides => 'text/event-stream' do
13 stream :keep_open do |out|
14 connections << out
15 out.callback { connections.delete(out) }
16 end
17 end
18
19 post '/' do
20 connections.each { |out| out << "data: #{params[:msg]}\n\n" }
21 204 # response without entity body
22 end
23
24 __END__
25
26 @@ layout
27 <html>
498bad91 » etehtsea
2012-07-18 Remove trailing whitespaces
28 <head>
29 <title>Super Simple Chat with Sinatra</title>
88406916 » rkh
2011-12-30 add examples directory
30 <meta charset="utf-8" />
498bad91 » etehtsea
2012-07-18 Remove trailing whitespaces
31 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
32 </head>
88406916 » rkh
2011-12-30 add examples directory
33 <body><%= yield %></body>
34 </html>
35
36 @@ login
37 <form action='/'>
38 <label for='user'>User Name:</label>
39 <input name='user' value='' />
40 <input type='submit' value="GO!" />
41 </form>
42
43 @@ chat
44 <pre id='chat'></pre>
45
46 <script>
47 // reading
48 var es = new EventSource('/stream');
49 es.onmessage = function(e) { $('#chat').append(e.data + "\n") };
50
51 // writing
52 $("form").live("submit", function(e) {
53 $.post('/', {msg: "<%= user %>: " + $('#msg').val()});
54 $('#msg').val(''); $('#msg').focus();
55 e.preventDefault();
56 });
57 </script>
58
59 <form>
60 <input id='msg' placeholder='type message here...' />
498bad91 » etehtsea
2012-07-18 Remove trailing whitespaces
61 </form>
Something went wrong with that request. Please try again.