Skip to content

Instantly share code, notes, and snippets.

@akoskovacs
Created June 15, 2017 00:15
Show Gist options
  • Save akoskovacs/24d192278ad2b254b0fa5f8a5de027d0 to your computer and use it in GitHub Desktop.
Save akoskovacs/24d192278ad2b254b0fa5f8a5de027d0 to your computer and use it in GitHub Desktop.
Sinatra SSE chatserver + JS client
<html>
<head><title>Chat</title></head>
<script>
window.onload = function() {
var chatRoom = new EventSource("/subscribe");
console.log(chatRoom);
chatRoom.onmessage = function(event) {
var cw = document.getElementById("chat-window");
cw.innerHTML += "<p>" + event.data + "</p><hr />";
console.log(event);
};
chatRoom.onerror = function(error) {
alert(error);
};
}
function onTalk() {
var xhr = new XMLHttpRequest();
var msg = document.getElementById('message-text');
if (msg == null || msg.value == "") {
alert("Type the message to send it!");
return false;
}
xhr.open('POST', '/message/' + msg.value, true);
xhr.send();
msg.value = "";
return false;
}
</script>
<body>
<h1>Welcome to Chat!!!</h1>
<div id="chat-window">
</div>
<div id="chat-talk">
<form action="" method="post" onsubmit="onTalk(); return false;">
<input id="message-text" type="text" name="message" placeholder="Say something" />
<input type="submit" name="submit" value="Say!" />
</form>
</div>
</body>
</html>
require 'sinatra'
set :server, :thin
connections = []
get '/' do
content_type 'text/html'
send_file 'chat.html'
end
get '/favicon.ico' do
404
end
get '/subscribe' do
content_type 'text/event-stream'
stream(:keep_open) do |out|
connections << out
connections.reject!(&:closed?)
end
end
def dispatch_msg(connections)
msg = params['message']
connections.each do |out|
out << "data: #{msg}\n\n"
#out.close
end
"'#{msg}' received"
end
post '/message/:message' do
dispatch_msg connections
end
get '/message/:message' do
dispatch_msg connections
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment