我已经创建了一个示例,说明 Sinatra 和 Faye 如何可以简单地一起工作。你可以在这里查看: https ://github.com/eterry1388/sinatra-faye-example
你config.ru
可能看起来像这样:
require 'faye'
require 'sinatra'
set :port, 9292
set :faye_client, Faye::Client.new( 'http://localhost:9292/faye' )
set :saved_data, Hash.new( [] )
get '/' do
# This loads the saved data so if the web page is refreshed
# or a new client connects, the data persists.
@saved_data = settings.saved_data
erb :index
end
post '/' do
channel = params['channel']
message = params['message']
# Send data out to connected clients
settings.faye_client.publish( channel, message )
# Save data for future clients
settings.saved_data[channel] += [message]
redirect to( '/' )
end
Faye::WebSocket.load_adapter 'thin'
use Faye::RackAdapter, mount: '/faye', timeout: 45, extensions: []
run Sinatra::Application
你index.erb
可能看起来像这样:
<script type="text/javascript" src="http://localhost:9292/faye/client.js"></script>
<script type="text/javascript">
var faye_client = new Faye.Client( 'http://localhost:9292/faye' );
faye_client.subscribe( '/blue', function( data ) {
var div = $( 'ul#blue-messages' ).append( '<li>' + data + '</li>' );
});
faye_client.subscribe( '/green', function( data ) {
var div = $( 'ul#green-messages' ).append( '<li>' + data + '</li>' );
});
$( document ).ready( function() {
$( 'button#submit' ).click( function() {
$.post('/',
$( 'form#send-message' ).serialize(),
function() {
$( 'textarea#message' ).val( '' );
});
});
});
</script>
<h2>Send message</h2>
<form id="send-message">
<label for="channel">Channel</label>
<select name="channel" id="channel" class="form-control">
<option>/blue</option>
<option>/green</option>
</select>
<label for="message">Message</label>
<textarea name="message" id="message" class="form-control"></textarea>
</form>
<button id="submit" class="btn btn-success">Send</button>
<h2>Blue messages</h2>
<ul id="blue-messages">
<%
# The below block is only used for loading historical
# saved data, not the Faye data!
%>
<% @saved_data['/blue'].each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
<h2>Green messages</h2>
<ul id="green-messages">
<%
# The below block is only used for loading historical
# saved data, not the Faye data!
%>
<% @saved_data['/green'].each do |message| %>
<li><%= message %></li>
<% end %>
</ul>