Class: WsIo
- Inherits:
-
Object
- Object
- WsIo
- Defined in:
- lib/ws-io.rb
Class Attribute Summary collapse
-
.ws ⇒ Object
Returns the value of attribute ws.
Class Method Summary collapse
- .escape(output) ⇒ Object
- .fake_io ⇒ Object
- .input(msg) ⇒ Object
- .output ⇒ Object
- .start(domains = ["*"], port = 8080) ⇒ Object
- .stop ⇒ Object
- .stop_server ⇒ Object
- .unfake_io ⇒ Object
Instance Method Summary collapse
Class Attribute Details
.ws ⇒ Object
Returns the value of attribute ws.
6 7 8 |
# File 'lib/ws-io.rb', line 6 def ws @ws end |
Class Method Details
.escape(output) ⇒ Object
108 109 110 |
# File 'lib/ws-io.rb', line 108 def escape(output) ERB::Util.html_escape(output.gsub(/\e\[[^m]+m/, '')) if output end |
.fake_io ⇒ Object
66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/ws-io.rb', line 66 def fake_io @in_read, @in_write = IO.pipe @stdin = STDIN.clone STDIN.reopen(@in_read) @stdout = STDOUT.clone @stderr = STDERR.clone @out_read, @out_write = IO.pipe STDOUT.reopen(@out_write) STDERR.reopen(@out_write) g 'fake_io' end |
.input(msg) ⇒ Object
100 101 102 |
# File 'lib/ws-io.rb', line 100 def input(msg) @in_write.puts(msg + "\n") end |
.output ⇒ Object
104 105 106 |
# File 'lib/ws-io.rb', line 104 def output @out_read.gets end |
.start(domains = ["*"], port = 8080) ⇒ Object
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 |
# File 'lib/ws-io.rb', line 14 def start(domains = ["*"], port = 8080) fake_io threads = [] threads << Thread.start do @server = WebSocketServer.new(:accepted_domains => domains, :port => port) @server.run() do |ws| if ws.path == "/" ws.handshake() WsIo.ws = ws while data = ws.receive() WsIo.input(data) end else ws.handshake("404 Not Found") end stop_server end end threads << Thread.start do begin yield ensure stop_server end end threads << Thread.start do loop do break if @ws && @ws.instance_variable_get(:@socket).closed? if @ws begin @ws.send(escape(output)) rescue # ignore! end end end end threads.each do |thread| thread.join end rescue SignalException, StandardError unfake_io rescue Exception unfake_io raise end |
.stop ⇒ Object
95 96 97 98 |
# File 'lib/ws-io.rb', line 95 def stop stop_server unfake_io end |
.stop_server ⇒ Object
89 90 91 92 93 |
# File 'lib/ws-io.rb', line 89 def stop_server ws.close @server.tcp_server.close g 'stop_server' end |
.unfake_io ⇒ Object
78 79 80 81 82 83 84 85 86 87 |
# File 'lib/ws-io.rb', line 78 def unfake_io STDIN.reopen(@stdin) STDOUT.reopen(@stdout) STDERR.reopen(@stderr) @in_read.close @in_write.close @out_write.close @out_read.close g 'unfake_io' end |
Instance Method Details
#g(*args) ⇒ Object
11 |
# File 'lib/ws-io.rb', line 11 def g(*args);end |