Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'em-websocket'
- require 'yajl'
- require 'haml'
- require 'sinatra/base'
- require 'thin'
- $channel = EM::Channel.new
- EventMachine.run do
- class App < Sinatra::Base
- get '/' do
- haml :index
- end
- end
- EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 8080) do |ws|
- ws.onopen {
- sid = $channel.subscribe { |msg| ws.send msg }
- ws.onmessage { |msg| $channel.push msg}
- 1.upto(5) {|i| sleep 3; ws.send "Hello #{i}"}
- }
- end
- App.run!({:port => 3000})
- end
- !!!
- %html{:lang => "en"}
- %head
- %link{:href => "/css/bootstrap.css", :rel => "stylesheet"}
- %body
- %div#show
- %script{:src => "http://code.jquery.com/jquery-1.7.2.min.js"}
- %script{:src => "/js/bootstrap.js"}
- %script{:src => "/js/app.js"}
- $(function(){
- ws = new WebSocket("ws://localhost:8080");
- ws.onmessage = function(evt) {
- if (evt.data!='done'){
- document.getElementById("show").innerHTML = evt.data;
- }
- };
- });
- require 'em-websocket-client'
- def send text
- EM.run do
- conn = EventMachine::WebSocketClient.connect("ws://localhost:8080")
- conn.callback do
- conn.send_msg text
- conn.send_msg "done"
- end
- conn.stream do |msg|
- puts "<#{msg}>"
- if msg.data == "done"
- conn.close_connection
- end
- end
- conn.disconnect do
- EM::stop_event_loop
- end
- end
- end
- 1.upto(5) do |i|
- sleep 3
- send "Hello #{i}"
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement