No commit activity in last 3 years
No release in over 3 years
Adds a JSON layer to a plain Eventmachine socket connection
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

>= 0

Runtime

 Project Readme

em_json_connection

This tiny gem adds a JSON layer to a plain Eventmachine socket connection. Normally when you use socket connections it’s your job to implement a protocol that defines a) where messages end and b) how messages are encoded. em_json_connection adds Yajl powered JSON en- and decoding to the game so all you do is writing stuff to the socket thats JSON encodable (Strings, Arrays, Hashes) and implement a callback on the other side that’s called each time Yajl has decoded a complete JSON entity.

See example.rb for… well… an example. Note the minimal setup for client and server classes:

Server:

module Server
  include EM::JsonConnection::Server
  
  def json_parsed(hash)
    puts "Client sent: #{hash}"
    
    send_data hash
  end
end

Sending data is simply done with the known Eventmachines #send_data method.

Client:

module Client
  include EM::JsonConnection::Client
  
  def json_parsed(hash)
    puts "Server responded: #{hash}"
  end
end

Running the server:

Then you start the server in your Eventmachine eventloop like this:

EM.run do
  Server.start_at '/tmp/foo'
  
  EM.add_timer(5) do
    puts 'stopping server'
    EM.stop
  end
end

Running the client:

EM.run do
  c = Client.connect_to '/tmp/foo'
  
  EM.add_periodic_timer 1 do
    c.send_data({:pid => Process.pid})
  end
  
  EM.add_timer(5) do
    puts 'stopping client'
    EM.stop
  end
end

Easy as pie! Have fun!