Ruby Websocket and Real-time App Tutorial

In this post I would like to present a small tutorial, I hope it will serve as a good introduction to web-socket api.

Websocket Server
In the part we focus on server part. In ruby we use eventmachine, em-websocket gem to install websocket server.
To install eventmachine run gem install eventmachine
To install em-websocket run gem install em-websocket
Make a file server.rb and implement codes below:

server.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
require 'eventmachine'
require 'em-websocket'

EventMachine.run {
  EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8080) do |ws|
    ws.onopen {
      puts "WebSocket connection open"
    }

    ws.onmessage { |msg|
      puts msg
      ws.send(msg)
    }

    ws.onclose {
      puts "WebSocket connection closed"
    }
  end
}

What the code does is creates a websocket-server which listens at localhost:8080. Callbacks have been provided for open and close events, so when a client creates a connection or a connection gets closed the associated callbacks print an appropriate message to the terminal. And callbacks have been provided for message event when a client send the message.

To run websocket server run ruby sever.rb

Websocket Client
So far, so good. But the main purpose of a websocket server is to get the message from client and relay data to the client. How do we do that? Turns out that is pretty simple too.
Make a file index.html and implement codes below:

index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<html>
<head>
  <title>Websocket GeeKhmer</title>
  <script type="text/javascript">
    var ws = null;
    function init() {
      ws = new WebSocket("ws://localhost:8080");
      ws.onopen = function() {
        console.log("Connection is opened");
      }

      ws.onclose = function() {
        console.log("Connection is closed");
      }

      ws.onmessage = function(msg) {
        document.getElementById("display").innerHTML = msg.data;
      }
    }

    function send() {
      ws.send(document.getElementById("txt").value);
    }
  </script>
</head>
<body onload="init();">
  <h2>WebSocket GeeKhmer</h2>
  <input type="text" id="txt">
  <input type="button" onclick="send();" value="Send">
  <p id="display"></p>
</body>
</html>

Feel free to provide your suggestions and to point out errors.