I am attempting to create a minimal Websocket implementation using Cramp framework. Where as Cramp successfully renders normal web content, I run into trouble when I try to use HTML5 websockets.
My action class is as follows :
Cramp::Websocket.backend = :thin
class HomeAction < Cramp::Action
self.transport = :websocket
keep_connection_alive
on_data :recv_data
def recv_data data
puts "got message"
puts "#{data}"
render "Hello world"
end
end
My javascript code is as follows :
$(function(){
window.socket = new WebSocket("ws://localhost:3000/game");
socket.onmessage = function(evt){
console.log(evt.data);
socket.close();
}
socket.onclose = function(evt) {
console.log("end");
}
socket.onopen = function() {
console.log("Now open!");
socket.send("Hello");
}
})
The server (thin) detects when data is sent but the text that is read is garbled.
the encoding of the data is ASCII-8BIT (puts data.encoding
prints "ASCII-8BIT"). However forcing UTF encoding through data.force_encoding('UTF-8') does not resolve the issue. In addition after forcing encoding - data.valid_encoding?
returns false where as it was true before forcing.
I have tested the app in ruby-1.8.7 as well as ruby-1.9.3 . The output is same in both scenarios.
Another weird thing is that in client side the onmessage event is never fired.
Also, if I remove keep_connection_alive call from HomeAction the connection immediately terminates after the data is received and still the client does not receive the data being sent by server ("Hello world").
I have tested the app in Google chrome (latest version) and Mozilla firefox (latest version). The problem remains exactly the same in both of them. My operating system is Ubuntu 12.04 LTS (Precise Pangolin).
Any help in this regard would be strongly appreciated.
I have been running into the same thing, and it seems to be an issue with the released version of the cramp 0.15.1 gem versus what you get from the github repo (https://github.com/lifo/cramp) thought is still marked as 0.15.1.
Try this experiment which works for me:
Change your gemfile, instead of just
Include the local copy of code:
Erase your Gemfile.lock and re-bundle, see that bundler now reports it will use the local copy of the cramp gem
It would appear there is either a fix in github they have not released yet (but have not incremented the working version in their gemspec) or some other version snafu, but either way the code in GH works whereas a "gem install cramp" doesn't give you working code for websockets.