Created
June 23, 2020 04:49
-
-
Save beccasaurus/cfb7bdc65c5581f8cbc7f5f478427138 to your computer and use it in GitHub Desktop.
Simple Ruby Websockets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source 'http://rubygems.org' | |
gem 'em-http-request', :require => 'em-http' | |
gem 'em-websocket' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# = 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