opal / opal-browser

Browser support for Opal.
MIT License
115 stars 36 forks source link

Browser::Socket won't handle events when connected to websocket-rack server. #24

Closed tioteath closed 5 years ago

tioteath commented 10 years ago

Here's my server code:

require 'rack/websocket'

class WebSocket < Rack::WebSocket::Application

  def on_open env
    EM.add_periodic_timer 5 do
      send_data "ping"
    end
    send_data 'Welcome!'
  end

  def on_message env, msg
    puts "message received: " + msg
  end
end

Opal application:

require 'opal'
require 'browser'
require 'browser/socket'
require 'browser/console'

Browser::Socket.new "ws://#{$window.location.host}/socket" do

  on :open do
    $console.log "Connection opened to host: #{$window.location.host}"
    every 1 do
      $console.log 'Sending ping'
      puts "ping"
    end
  end

  on :message do |e|
    $console.log "Received #{e.data}"
    puts 'pong' if e.data.eql? 'ping'
  end
end

config.ru:

require 'bundler'
Bundler.require

map '/socket' do
  run socket
end

map '/' do
  app = Opal::Server.new do |server|
    server.append_path 'app'
    server.main = 'application'
    server.index_path = File.join 'app', 'views', 'index.erb'
  end
  run app
end

index.erb:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <%= javascript_include_tag 'application' %>
</head>
<body>

</body>
</html>

Both websocket-rack and Browser::Socket are working fine, when are tested with third party tools (i.e. simple Javascript example, in case of websocket-rack, and echo.websocket.org, in case of Browser::Socket), but failed to interact with each other. I cannot see any replies on both side. Seems this is a problem of Browser::Socket, as it hangs with Status Code: HTTP/1.1 101 Switching Protocols, i.e. I cannot see HTTP/1.1 101 Web Socket Protocol Handshake, like that is in case of echo.websocket.org.