/socket-wrench

A websocket abstraction framework written in Ruby and JavaScript

Primary LanguageJavaScript

Socket Wrench - WebSockets made easy (way easy)

Socket Wrench consists of two parts, a server written in Sinatra/em-websocket and a client side javascript library.
Socket wrench makes it dead simple to write websocket driven applications that take advantage of this awesome technology.

TODO: need to fix syntax for declaring the protocols/commands
TODO: Support for multiple "channels" within a protocol to allow for something like a chat system with multiple rooms

High level example for a chat room (even though this is mostly pseudo code, the actual code using Socket Wrench wouldn't be much longer):

Protocol: chat
Commands: join, leave, update

Server side (this is all the code you'd have to write):

    @@user_list = []

    @@socket = SocketWrench.new(9001)

    @@socket.protocol("chat") do

        on "update" do
          # Send updates to all clients in the channel
          send_to_channel("update", data)
        end

        on "join" do
          unless @@user_list.include? data['username']
            # Tell the client the user list
            send_to_client("user_list", {'list' => @@user_list})
            @@user_list.push(data['username'])
            # Tell the channel that somebody joined
            send_to_channel("join", data)
          end
        end

        on "leave" do
          if @@user_list.include? data['username']
            # Tell the channel that somebody left
            send_to_channel("leave", data)
            @@user_list.delete(data['username'])
          end
        end

        on "username_check" do
          send_to_client("username_check", @@user_list.include?(data['username']))
        end

    end

    @@socket.begin_listening
-------------------------
Client side JavaScript:

socket = SocketWrench.create("url", "port", "chat");
socket.on("join", function (data) {
    addToUserList(data.username);
    writeChatMessage(null, data.username + " joined the chat!");
});

socket.on("leave", function (data) {
    removeFromUserList(data.username);
    writeChatMessage(null, data.username + " left the chat!");
});

socket.on("update", function (data) {
    writeChatMessage(data.username, data.message);
});