-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrun.rb
66 lines (54 loc) · 1.28 KB
/
run.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
require 'sinatra'
require 'eventmachine'
# disable sinatra's autorun. We'll start it up
# in a separat thread later on
disable :run
class WebApp < Sinatra::Base
# send the message to all connected clients
def self.send_event(event = {:event => 'message', :data => 'test'})
connections.each do |c|
if c.closed
connections.delete(c)
else
c << "event: #{event[:event]}\n"
c << "data: #{event[:data]}\n\n"
end
end
end
def self.connections
@connections ||= []
end
get '/evented' do
content_type 'text/event-stream'
stream(:keep_open) do |out|
WebApp.connections << out
end
end
end
class Handler < EM::Connection
def receive_data(data)
puts "Received event: #{data.inspect}"
parsed_data = data.chomp.split(":") || 0
if parsed_data.size == 2
WebApp.send_event :event => parsed_data[0], :data => parsed_data[1]
else
puts "Could not parse data"
end
end
end
class UdpServer
HOST = '127.0.0.1'
PORT = '3333'
def self.run
EM::open_datagram_socket(HOST, PORT, Handler)
end
end
# Start up sinatra and
if __FILE__ == $PROGRAM_NAME
EM.run do
WebApp.run!
UdpServer.run
Signal.trap("INT") { EventMachine.stop }
Signal.trap("TERM") { EventMachine.stop }
end
end