daily pastebin goal
66%
SHARE
TWEET

Untitled

a guest Nov 18th, 2018 95 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. require 'sinatra'
  2.  
  3. connections = []
  4.  
  5. get '/' do
  6.   erb :index
  7. end
  8.  
  9. get '/stream' do
  10.   content_type 'text/event-stream'
  11.   stream(:keep_open) do |out|
  12.     connections << out
  13.     out.callback { connections.delete(out) }
  14.   end
  15. end
  16.  
  17. post '/message' do
  18.   connections.each { |out| out << "data: #{params[:msg]}\n\n" }
  19.   204
  20. end
  21.  
  22. __END__
  23.  
  24. @@ index
  25.   <article id="log"></article>
  26.  
  27.   <form id="form">
  28.     <input type="text" name="message" id="message" placeholder="Chat" autofocus>
  29.   </form>
  30.  
  31.   <script>
  32.     var source = new EventSource('/stream');
  33.     source.onmessage = function (event) {
  34.       log.innerText += '\n' + event.data;
  35.     };
  36.  
  37.     form.addEventListener('submit', function (e) {
  38.       e.preventDefault();
  39.  
  40.       var request = new XMLHttpRequest();
  41.       request.open('POST', '/message', true);
  42.       request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  43.       request.send('msg=' + message.value);
  44.  
  45.       message.value = '';
  46.     }, false);
  47.   </script>
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top