Skip to content

Instantly share code, notes, and snippets.

@beccasaurus
Created June 23, 2020 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beccasaurus/cfb7bdc65c5581f8cbc7f5f478427138 to your computer and use it in GitHub Desktop.
Save beccasaurus/cfb7bdc65c5581f8cbc7f5f478427138 to your computer and use it in GitHub Desktop.
Simple Ruby Websockets
source 'http://rubygems.org'
gem 'em-http-request', :require => 'em-http'
gem 'em-websocket'
# = Simple "Ping:Pong" websocket server
#
# See https://github.com/igrigorik/em-http-request/blob/master/examples/websocket-server.rb
require 'rubygems'
require 'em-websocket'
HOST, PORT = '0.0.0.0', 8000
EventMachine.run do
puts '='*80, "Starting websockets server at socket://#{HOST}:#{PORT}", '='*80
EventMachine::WebSocket.start(:host => HOST, :port => PORT) do |socket|
socket.onopen do
puts "#{Time.now.strftime('%H:%M:%S')} : Client connected", '-'*80
socket.send "Hello client!"
EventMachine.add_periodic_timer(1) { socket.send '.' } # Tick...
end
socket.onclose do
puts "#{Time.now.strftime('%H:%M:%S')} : Client disconnected", '-'*80
end
socket.onmessage do |msg|
puts "Recieved message: #{msg.inspect}"
socket.send "Hi there, I thought I'd let you know that we received your message: #{msg.inspect}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment