Skip to content

Instantly share code, notes, and snippets.

@ngarneau ngarneau/chat.rb forked from rkh/chat.rb
Created Dec 14, 2011

What would you like to do?
Simple Chat Application using the Sinatra Streaming API
# coding: utf-8
require 'sinatra'
set server: 'thin', connections: []
get '/' do
halt erb(:login) unless params[:user]
erb :chat, locals: { user: params[:user].gsub(/\W/, '') }
get '/stream', provides: 'text/event-stream' do
stream :keep_open do |out|
settings.connections << out
out.callback { settings.connections.delete(out) }
post '/' do
settings.connections.each { |out| out << "data: #{params[:msg]}\n\n" }
204 # response without entity body
@@ layout
<title>Super Simple Chat with Sinatra</title>
<meta charset="utf-8" />
<script src=""></script>
<body><%= yield %></body>
@@ login
<form action='/'>
<label for='user'>User Name:</label>
<input name='user' value='' />
<input type='submit' value="GO!" />
@@ chat
<pre id='chat'></pre>
// reading
var es = new EventSource('/stream');
es.onmessage = function(e) { $('#chat').append( + "\n") };
// writing
$("form").live("submit", function(e) {
$.post('/', {msg: "<%= user %>: " + $('#msg').val()});
$('#msg').val(''); $('#msg').focus();
<input id='msg' placeholder='type message here...' />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.