Skip to content

Instantly share code, notes, and snippets.

@ezura
Created September 27, 2014 09:49
Show Gist options
  • Save ezura/f97940edb4d790101dde to your computer and use it in GitHub Desktop.
Save ezura/f97940edb4d790101dde to your computer and use it in GitHub Desktop.
require "em-websocket"
require 'json'
require 'sinatra/base'
require 'thin'
$stdout.sync = true
# FIX_ME: port とか host とか直打ちしない
EventMachine.run {
@globalChannel = EM::Channel.new
@channels = Hash.new { |hash, key| hash[key] = EM::Channel.new }
class App < Sinatra::Base
get '/' do
"Hello!"
end
# locahost:3001/states/1
post '/states/:id' do
# params[:id]
params = JSON.parse request.body.read
puts params
@globalChannel.push "@globalChannel.push"
end
end
EM::WebSocket.start(host: "localhost", port: 3002) do |ws|
ws.onopen {
sid = @globalChannel.subscribe { |message| ws.send(message) }
ws.onmessage { |msg|
recieve_data = JSON.parse(msg)
channel.push msg
}
ws.onclose {
@globalChannel.unsubscribe(sid)
# @channels.values.each { |value| value.unsubscribe(sid) }
}
@pushData = lambda { |data| @globalChannel.push data }
}
end
puts "------------ #{Process.pid} ------------"
App.run!(:port => 3001)
}
# error 内容
# NoMethodError - undefined method `push' for nil:NilClass:
# websocket-server/main.rb:23:in `block in <class:App>'
@ezura
Copy link
Author

ezura commented Oct 10, 2014

解決しました。
@globalChannel のスコープの問題でした。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment