Faye websocket - 200 error - ruby-on-rails

I'm building an app that supports realtime bid using Faye-websocket. But I got this 200 error and I have no idea what problem it is.
Error:
WebSocket connection to 'ws://localhost/auctions/3' failed: Error during WebSocket handshake: Unexpected response code: 200
SocketConnection.rb
require 'faye/websocket'
require 'websocket/extensions'
require 'thread'
require 'json'
class SocketConnection
KEEPALIVE_TIME = 15 # in seconds
def initialize app
#app = app
end
def call env
#env = env
if Faye::WebSocket.websocket?(env)
socket = Faye::WebSocket.new env
socket.ping 'Mic check, one, two' do
p [:ping, socket.object_id, socket.url]
end
socket.on :open do |event|
p [:open, socket.object_id, socket.url]
p [:open, socket.url, socket.version, socket.protocol]
end
socket.rack_response
else
#app.call(env)
end
end
end

I firgured out the problem. It requires a server to support socket connection. In my case, I use thin server. All errors are fixed

Related

Rails - Visiting URLs in a rake task - Sockets Error

I'm attempting to create a rake tasks that visits a series of URLs, logs the status code, and then prints them to console. My code is as follows:
require 'csv'
require 'net/http'
require "open-uri"
namespace :routes do
desc "check status codes"
task check_301s: :environment do
# open_csv
# edit_urls
generate_routes
# visit_urls
# log_status_codes
visit_and_log_routes
# give_results
end
def generate_routes
csv = CSV.open('lib/better.csv', headers: true)
#urls = []
csv.each do |row|
#urls << row['url'].gsub('foo', 'localhost:3000')
end
end
def visit_and_log_routes
responses = []
#urls.each do |url|
http = Net::HTTP.new(url, 3000)
response = http.request_get('/')
responses << response
end
puts responses
end
end
I'm receiving the following error code when running this from terminal:
SocketError: Failed to open TCP connection to localhost:3000/children-centre/london/greenwich/eltham-childrens-centre/join:3000 (getaddrinfo: nodename nor servname provided, or not known)
I'm not sure if there is an easier way to visit URLs and log their status code, if so please let me know how to do it, and if not then how I can correct this error message. I'm assuming I'm simply leaving out the relevant options but am not sure how / where to add them.
For anyone making the same impressive error I was... the route needs http:// at the start instead of just localhost:3000

rails global variable inaccessible in thread

I'm using Faye websockets and Redis to attempt a master/client websocket setup for a slideshow presentation.
The clients' should all follow along with the master (i.e. the master moves forward a slide, a message is sent out to all of the clients, and they all move forward a slide).
The issue I'm having is that my list of client websockets is empty when I access inside the thread created in the initialize function. The separate thread is necessary as Redis' 'subscribe' is a blocking function.
This file is a middleware and runs on app boot up.
I know that the point of global variables in rails is that they're shared across threads, but in my case something seems to be preventing it.
Is there a way to store a list of websockets in a globally accessible place? Globally, as in, for all running instances of the app on the same server.
(can't use Redis for that cause it can't store objects).
require 'faye/websocket'
require 'redis'
class WsCommunication
KEEPALIVE_TIME = 15 #seconds
CHANNEL = 'vip'
def initialize(app)
#app = app
$clients = []
uri = URI.parse(ENV['REDISCLOUD_URL'])
Thread.new do
redis_sub = Redis.new(host: uri.host, port: uri.port, password: uri.password)
redis_sub.subscribe(CHANNEL) do |on|
on.message do |channel, msg|
puts 'client list on thread'
puts $clients
#### prints nothing
$clients.each { |ws| ws.send(msg) }
end
end
end
end
def call(env)
if Faye::WebSocket.websocket?(env)
ws = Faye::WebSocket.new(env, nil, {ping: KEEPALIVE_TIME})
ws.on :open do |event|
$clients << ws
end
ws.on :message do |event|
puts 'client list'
puts $clients
### prints the full list of clients
$redis.publish(CHANNEL, event.data)
end
ws.on :close do |event|
$clients.delete(ws)
ws = nil
end
# Return async Rack response
ws.rack_response
else
#app.call(env)
end
end
end

Testing Faye for message success from Rails app to Faye server

I have my main Rails server and a separate Faye server (localhost:9292) setup correctly to handle messaging. Everything is working as expected but I'm having problems with trying to test it.
I'm trying to setup my test as a worker that runs once a day, and if a message isn't received I want to have the app send me an email. Here's what I have so far based on the info in Faye's docs
require 'eventmachine'
require 'faye/websocket'
class PingFayeServerWorker < BaseWorker
def initialize
end
def process
EventMachine.run {
client = Faye::Client.new('http://localhost:9292/faye')
client.set_header('Authorization', 'OAuth abcd-1234')
client.subscribe('/foo') do |message|
puts message.inspect
end
publication = client.publish('/foo', 'text' => 'Hello world')
publication.callback do
puts 'Message received by server!'
end
publication.errback do |error|
puts 'There was a problem: ' + error.message
end
}
end
end

Open socket in ruby on rails

I want to make socket in ruby. First I run ruby - server.rb in cmd
require 'socket' # Get sockets from stdlib
server = TCPServer.open(2000) # Socket to listen on port 2000
loop { # Servers run forever
Thread.start(server.accept) do |client|
puts "Connected!!!"
client.puts(Time.now.ctime) # Send the time to the client
client.puts "Closing the connection. Bye!"
client.close # Disconnect from the client
end
}
then in my controller :
class StaticPagesController < ApplicationController
helper :all
def home
Thread.new do
require 'socket' # Sockets are in standard library
hostname = 'localhost'
port = 2000
s = TCPSocket.open(hostname, port)
while line = s.gets # Read lines from the socket
puts line.chop # And print with platform line terminator
end
s.close # Close the socket when done
end
end
I don't know why it don't work, can someone help me ?
reference:http://www.tutorialspoint.com/ruby/ruby_socket_programming.htm

Getting rack error Rack::Lint::LintError: Status must be >=100 seen as integer

I'm trying to build my rack based ruby app, and I'm still new here, I'm using ruby 1.9.2 -p180
in my config.ru file I have:
require "rack"
require "./my_app.rb"
require "./auth.rb"
use Auth
run MyApp.new
Now main problem with Middleware Auth, simply, I want it to not continue MyApp if there were less than 2 params for the request and just print out something ( just for testing ) :
class Auth
def initialize(app)
#app = app
end
def call(env)
request = Rack::Request.new(env)
if request.params.count < 2
["200",{"Content-Type" => "text/plain"}, ["Hello World"]]
puts 'Working .. '
else
#app.call(env)
end
end
end
Now when I run my rack app :
rackup -s thin config.ru
And try to get the results :
curl http://localhost:9292/
I keep getting the following error :
Rack::Lint::LintError: Status must be >=100 seen as integer
/Users/Apple/.rvm/gems/ruby-1.9.2-p180/gems/rack-1.4.1/lib/rack/lint.rb:19:in `assert'
/Users/Apple/.rvm/gems/ruby-1.9.2-p180/gems/rack-1.4.1/lib/rack/lint.rb:425:in `check_status'
Of course if I run it with production mode I will not get this error.
Any help would be appreciated here .
Try using an integer for the status:
[200,{"Content-Type" => "text/plain"}, ["Hello World"]]
Instead of:
["200",{"Content-Type" => "text/plain"}, ["Hello World"]]

Resources