Skip to content

Instantly share code, notes, and snippets.

@jstorimer
Created August 9, 2012 06:46
Show Gist options
  • Save jstorimer/3301754 to your computer and use it in GitHub Desktop.
Save jstorimer/3301754 to your computer and use it in GitHub Desktop.

RocketSocket

This library was created out of my frustrations working with the Ruby's built-in Socket classes when writing Working With Sockets. It provides two functions: 1) A better way of building sockets with the common options that are more configurable/portable, and 2) A built-in way of framing messages in an safe and efficient manner. Nothing fancy.

RocketSocket::Build

socket = RocketSocket::Build.host('0.0.0.0').port(8080).ssl.read_timeout(60).write_timeout(10).listen(512).tcp
socket.write_timeout #=> 10
socket.host #=> '0.0.0.0'
socket.write('message')

Under the hood this builds up a chain of options that doesn't gets lazily evauluated. At any point you can call #socket to get back something that you can actually call #read and #write on, or you can just use the object you get back from the Build method and it will delegate the method calls to the underlying socket.

Potential alternate syntax...

socket = RocketSocket::Build(host: '0.0.0.0', port: 8080, ssl: true, read_timeout: 60, write_timeout: 10, tcp: true)
socket.write_timeout #=> 10
socket.host #=> '0.0.0.0'
socket.write('message')

RocketSocket::Messaging

This is a module that can be mixed in to any Socket-like object. This includes Ruby's built-in socket classes or an object returned from RocketSocket::Build.

socket = TCPSocket.new('127.0.0.1', 8080)
socket.extend RocketSocket::Messaging

socket.write_msg 'This will be sent as a single message with proper boundaries, rather than as a stream of data'

The other end of the connection could use a RocketSocket and receive the message like so:

socket = RocketSocket::Build.host('127.0.0.1').port(8080).accept_loop do |connection|
  connection.extend RocketSocket::Messaging
  connection.read_msg
end

Message Format

Full list of build options

Full list of messaging options (nonblock, works with select, etc)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment