Skip to content

Instantly share code, notes, and snippets.

@myobie
Last active December 19, 2015 05:48
Show Gist options
  • Save myobie/5906275 to your computer and use it in GitHub Desktop.
Save myobie/5906275 to your computer and use it in GitHub Desktop.
Using websockets not for websockets, but to trigger ajax.

So, I had this idea.

Basically, I don't really like using websockets for actual data transfer because it's too easy to miss one thing and get out of sync, especially with crappy mobile clients etc. However, I also hate polling. So, I thought why not just use websockets as notification service to tell the client that new data is available. Then the client can update however it sees fit and without changing much. All you have to do on the web server side of things is publish a message when any data changes. It could also become more granular by posting messages for when certain pieces of data are updated.

This also means that one could fallback to polling pretty easily for clients that aren't ready for websockets.

If you want to run this example:

> bundle
> ./ws_server
> ./web_server

then visit http://127.0.0.1:3000.

source "http://rubygems.org"
gem "em-hiredis"
gem "em-websocket"
gem "sinatra"
gem "redis"
gem "hiredis"
gem "thin"
GEM
remote: http://rubygems.org/
specs:
daemons (1.1.9)
em-hiredis (0.2.1)
hiredis (~> 0.4.0)
em-websocket (0.5.0)
eventmachine (>= 0.12.9)
http_parser.rb (~> 0.5.3)
eventmachine (1.0.3)
hiredis (0.4.5)
http_parser.rb (0.5.3)
rack (1.5.2)
rack-protection (1.5.0)
rack
redis (3.0.4)
sinatra (1.4.3)
rack (~> 1.4)
rack-protection (~> 1.4)
tilt (~> 1.3, >= 1.3.4)
thin (1.5.1)
daemons (>= 1.0.9)
eventmachine (>= 0.12.6)
rack (>= 1.0.0)
tilt (1.4.1)
PLATFORMS
ruby
DEPENDENCIES
em-hiredis
em-websocket
hiredis
redis
sinatra
thin
raise "Where is redis?" unless $redis
Item = Struct.new(:content) do
def self.updates_available!
$redis.publish $pub_key, "refresh"
end
def updates_available!
self.class.updates_available!
end
def self.all
raw_items = $redis.zrange $items_key, 0, -1
raw_items.map { |i| Item.new(i) }
end
def save
num = $redis.incr $items_inc_key
$redis.zadd $items_key, num, content
updates_available!
true
end
def destroy
$redis.zrem $items_key, content
updates_available!
true
end
end
The MIT License (MIT)
Copyright (c) 2013 Nathan Herald
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
function log() {
console && console.log && console.log(arguments);
}
function fetchItems() {
log("Fetching items...");
$.get("/items.json", {}, function(data) {
if (data && data.html) {
$("#content").html(data.html);
} else {
log("WTF", data);
}
}, "json");
}
function createItem(content, cb) {
log("Creating a new item...");
$.post("/items.json", { content: content }, function(data) {
if (data && data.success) {
log("Item was created. This function will not refresh the data on it's own.");
} else {
log("WTF", data);
}
if (cb) { cb(); }
}, "json");
}
$("form").submit(function(event) {
event.preventDefault();
var content = $("input.new_item_content").val();
if (content != "") {
$("button").attr("disabled", true).text("Adding...");
createItem(content, function() {
$("button").removeAttr("disabled").text("Add");
$("input.new_item_content").val("");
});
}
});
function removeItem(content, cb) {
log("Removing an item...");
$.post("/items.json", { content: content, _method: "delete" }, function(data) {
if (data && data.success) {
log("Item was removed. This function will not refresh the data on it's own.");
} else {
log("WTF", data);
}
if (cb) { cb(); }
}, "json");
}
$("#content").on("click", "a.harmful", function(event) {
event.preventDefault();
var content = $(this).prev("span").text();
removeItem(content);
});
// ws specific stuff
function newMessage(event) {
log("Server says there is new content, let's refresh the div.");
fetchItems();
}
var ws = new WebSocket("ws://127.0.0.1:4568");
ws.onmessage = newMessage;
require 'sinatra'
require 'redis'
require 'hiredis'
require 'json'
$redis = Redis.new url: ENV["REDIS_URL"], driver: :hiredis
$items_key = "items-set"
$items_inc_key = "items-set-inc-num"
$pub_key = "item-updates"
$js = File.read("./web.js")
require './item'
helpers do
def json(object)
JSON.generate object
end
end
get "/" do
@items = Item.all
erb :index
end
get "/items.json" do
@items = Item.all
html = erb :items, layout: false
json html: html
end
post "/items.json" do
item = Item.new params[:content]
item.save
json success: true
end
delete "/items.json" do
item = Item.new(params[:content])
item.destroy
json success: true
end
__END__
@@layout
<!doctype html>
<html>
<head>
<title>Websockets without websockets using websockets</title>
<style>
a.harmful {
color: red;
}
</style>
</head>
<body>
<%= yield %>
<script src="//cdnjs.cloudflare.com/ajax/libs/zepto/1.0/zepto.min.js"></script>
<script>
<%= $js %>
</script>
</body>
</html>
@@index
<div id="content">
<%= erb :items %>
</div>
<form>
<input class="new_item_content" placeholder="New Item">
<button type="submit">Add</button>
</form>
@@items
<ul>
<% @items.each do |item| %>
<li>
<span class="content"><%= item.content %></span>
<a href="#" class="harmful">del</a>
</li>
<% end %>
</ul>
require 'bundler/setup'
require './web_app'
run Sinatra::Application
#! /usr/bin/env sh
if [ -z $PORT ]
then
PORT=3000
fi
bundle exec thin -R web_config.ru -p $PORT start
require 'em-websocket'
require 'em-hiredis'
EM.run do
@channel = EM::Channel.new
@redis = EM::Hiredis.connect ENV["REDIS_URL"]
pubsub = @redis.pubsub
pubsub.subscribe("item-updates")
pubsub.on(:message) do |redis_channel, message|
@channel.push message
end
puts "Starting em-websocket on 127.0.0.1:4568"
EM::WebSocket.start(host: "127.0.0.1", port: "4568") do |ws|
ws.onopen do
sid = @channel.subscribe do |message|
puts "Setup."
ws.send message
end
ws.onmessage do |message|
puts "message for id #{sid}: #{message}"
end
ws.onclose do
puts "Teardown."
@channel.unsubscribe ws
end
end
end
end
require 'bundler/setup'
require './ws_app'
#! /usr/bin/env sh
if [ -z $PORT ]
then
PORT=4568
fi
bundle exec thin -R ws_config.ru -p $PORT start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment