Advertisement
Guest User

Untitled

a guest
Jul 28th, 2015
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. require 'em-websocket'
  2. require 'yajl'
  3. require 'haml'
  4. require 'sinatra/base'
  5. require 'thin'
  6.  
  7. $channel = EM::Channel.new
  8.  
  9. EventMachine.run do
  10. class App < Sinatra::Base
  11. get '/' do
  12. haml :index
  13. end
  14. end
  15.  
  16. EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 8080) do |ws|
  17. ws.onopen {
  18. sid = $channel.subscribe { |msg| ws.send msg }
  19. ws.onmessage { |msg| $channel.push msg}
  20. 1.upto(5) {|i| sleep 3; ws.send "Hello #{i}"}
  21. }
  22. end
  23. App.run!({:port => 3000})
  24. end
  25.  
  26. !!!
  27. %html{:lang => "en"}
  28. %head
  29. %link{:href => "/css/bootstrap.css", :rel => "stylesheet"}
  30. %body
  31. %div#show
  32. %script{:src => "http://code.jquery.com/jquery-1.7.2.min.js"}
  33. %script{:src => "/js/bootstrap.js"}
  34. %script{:src => "/js/app.js"}
  35.  
  36. $(function(){
  37. ws = new WebSocket("ws://localhost:8080");
  38. ws.onmessage = function(evt) {
  39. if (evt.data!='done'){
  40. document.getElementById("show").innerHTML = evt.data;
  41. }
  42. };
  43. });
  44.  
  45. require 'em-websocket-client'
  46.  
  47. def send text
  48. EM.run do
  49. conn = EventMachine::WebSocketClient.connect("ws://localhost:8080")
  50.  
  51. conn.callback do
  52. conn.send_msg text
  53. conn.send_msg "done"
  54. end
  55.  
  56. conn.stream do |msg|
  57. puts "<#{msg}>"
  58. if msg.data == "done"
  59. conn.close_connection
  60. end
  61. end
  62.  
  63. conn.disconnect do
  64. EM::stop_event_loop
  65. end
  66. end
  67. end
  68.  
  69. 1.upto(5) do |i|
  70. sleep 3
  71. send "Hello #{i}"
  72. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement