A simple Websocket-eventmachine example

Installation

server:

require 'websocket-eventmachine-server'

EM.run do

  WebSocket::EventMachine::Server.start(:host => "0.0.0.0", :port => 8080) do |ws|
    ws.onopen do
      puts "Client connected"
    end

    ws.onmessage do |msg, type|
      puts "Received message: #{msg}"
      ws.send msg, :type => type
    end

    ws.onclose do
      puts "Client disconnected"
    end
  end

end

client:

require 'websocket-eventmachine-client'
EM.run do

  ws = WebSocket::EventMachine::Client.connect(:uri => 'ws://localhost:8080')

  ws.onopen do
    puts "Connected"
  end

  ws.onmessage do |msg, type|
    puts "Received message: #{msg}"
  end

  ws.onclose do
    puts "Disconnected"
  end

  EventMachine.next_tick do
    ws.send "Hello Server!"
  end

end

client output:

Connected
Received message: Hello Server!

server output:

Client connected
Received message: Hello Server!

Resources

Tags:
Source:
1805hrs.txt
Published:
09-11-2013 18:05