lib/template/wsserver.rb in browser_app_base-0.0.8 vs lib/template/wsserver.rb in browser_app_base-0.0.9
- old
+ new
@@ -1,29 +1,55 @@
require "./server_app_base"
require "json"
require "cgi"
+require "thread"
def config_json_hash(json)
config = {}
json.each do |j|
config[j["name"]] = j["value"]
end
return config
end
+$ws_exit_thread = nil
+
class WsServer < Sinatra::Base
- $ws_list = []
+ def initialize
+ super
+ @ws_list = []
+ @ws_lock = Mutex.new
+ end
+
+ def ws_send(str)
+ @ws_lock.synchronize do
+ if @ws_list[0] != nil
+ @ws_list[0].send(str)
+ end
+ end
+ end
+
json_config = nil
exec_thread = nil
get "" do
if !request.websocket?
"no supported"
else
request.websocket do |ws|
ws.onopen do
- ws.send("startup:#{$startup_file}")
- $ws_list << ws
+ puts "ws.open"
+ @ws_lock.synchronize do
+ @ws_list << ws
+ $app.set_ws(ws)
+ pp "ws=#{ws}"
+ end
+ ws_send("startup:#{$startup_file}")
+ puts "ws_exit_thread=#{$ws_exit_thread}"
+ if $ws_exit_thread != nil
+ puts "ws_exit_thread kill"
+ Thread.kill $ws_exit_thread
+ end
end
ws.onmessage do |msg|
puts msg
if msg =~ /^exec:/
if exec_thread == nil
@@ -32,26 +58,26 @@
$app.set_config(json_config)
argv = msg.gsub(/^exec:/, "")
exec_thread = Thread.new {
begin
$app.start(argv.split(",")) do |out|
- ws.send(out)
+ ws_send(out)
end
- ws.send("app_end:normal")
+ ws_send("app_end:normal")
rescue
puts $!
puts $@
puts "app_end:err"
- ws.send("app_end:error")
+ ws_send("app_end:error")
ensure
puts "exit thread"
exec_thread = nil
end
}
else
puts "app_end:err"
- ws.send("app_end:error")
+ ws_send("app_end:error")
end
end
if msg =~ /^stop/
if exec_thread
$app.stop
@@ -81,26 +107,30 @@
Thread.new {
system "#{json_config["editor"]} #{CGI.unescapeHTML(file)}"
}
end
+ # アプリケーション終了
if msg == "exit"
- unless ENV["OCRA"] == "true"
- halt
- #exit
- end
+ #halt
+ exit
end
end
+
+ # close websocket
ws.onclose do
puts "websocket closed"
- $ws_list.delete(ws)
- puts $ws_list.size
- if $ws_list.size == 0
- puts ENV["OCRA"]
- unless ENV["OCRA"] == "true"
+ @ws_lock.synchronize do
+ @ws_list.delete(ws)
+ end
+ puts @ws_list.size
+ if @ws_list.size == 0
+ $ws_exit_thread = Thread.start {
+ sleep 1
#halt
exit
- end
+ }
+ puts "ws_exit_thread=#{$ws_exit_thread}"
end
end
end
end
end