Skip to content

Instantly share code, notes, and snippets.

@amaltson
Created October 23, 2015 17:12
Show Gist options
  • Save amaltson/5fadbca01c39de777cc5 to your computer and use it in GitHub Desktop.
Save amaltson/5fadbca01c39de777cc5 to your computer and use it in GitHub Desktop.
Start with `thin start` and then connect to the client with just ruby websocket-client.rb
require 'eventmachine'
require 'rack'
require 'thin'
require 'faye/websocket'
Faye::WebSocket.load_adapter('thin')
App = lambda do |env|
if Faye::WebSocket.websocket?(env)
ws = Faye::WebSocket.new(env)
ws.on :message do |event|
ws.send(event.data)
end
ws.on :close do |event|
p [:close, event.code, event.reason]
ws = nil
end
# Return async Rack response
ws.rack_response
else
# Normal HTTP request
[200, {'Content-Type' => 'text/plain'}, ['Hello']]
end
end
run App
require 'faye/websocket'
require 'eventmachine'
EM.run {
ws = Faye::WebSocket::Client.new("ws://#{ARGV[0]}:3000")
ws.on :open do |event|
p [:open]
ws.send('Hello, world!')
end
ws.on :message do |event|
p [:message, event.data]
end
ws.on :close do |event|
p [:close, event.code, event.reason]
ws = nil
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment