WebSockets

suggest change

HTTP is request/response: the client asks, the server answers, and the server can't send anything on its own. A WebSocket is a long-lived, two-way connection. It starts as an ordinary HTTP request, then both sides "upgrade" the same TCP connection and from then on either side can send a message at any time. Chat, live dashboards, notifications, multiplayer games and collaborative editors all use WebSockets.

The protocol (RFC 6455) has two parts:

Ruby has no WebSocket support in the standard library. This article first builds a tiny server by hand on top of TCP sockets to show how the protocol works, then uses the async-websocket gem for real servers and clients. It is built on fibers and the Async gem, so one process handles thousands of mostly idle connections.

The examples were run with Ruby 4.0, async 2.46, async-http 0.105, async-websocket 0.30 and falcon 0.57:

gem install async-websocket async-http falcon

The gems use IO::Buffer, which makes Ruby print a warning that it is experimental. The examples turn it off with Warning[:experimental] = false.

The handshake

The server proves it understands WebSockets by appending a fixed GUID to the client's key, hashing it with SHA-1 and Base64-encoding the result:

require 'digest'
require 'securerandom'

GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' # fixed by RFC 6455

def accept_key(client_key)
  [Digest::SHA1.digest(client_key + GUID)].pack('m0') # m0 = strict Base64
end

# The example from RFC 6455
puts accept_key('dGhlIHNhbXBsZSBub25jZQ==')

# A client sends a fresh random 16-byte key for every connection
key = [SecureRandom.random_bytes(16)].pack('m0')
puts key.size
s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
24

This isn't security. It only makes sure that a plain HTTP server or a caching proxy can't accidentally pretend to speak WebSocket.

A WebSocket server by hand

Here is a complete (if minimal) echo server using only socket and digest. It handles one client, reads the handshake headers, replies with 101, and then decodes frames.

Each frame starts with 2 bytes: the FIN bit plus a 4-bit opcode (1 text, 2 binary, 8 close, 9 ping, 10 pong), then a mask bit plus a 7-bit length. A length of 126 or 127 means the real length follows in 2 or 8 bytes. Frames from client to server must be masked: the payload is XOR-ed with a 4-byte key sent in the frame. Frames from server to client are never masked.

# raw_server.rb
require 'socket'
require 'digest'

GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'

# Read one frame: returns [opcode, payload]
def read_frame(io)
  b0, b1 = io.read(2).bytes
  opcode = b0 & 0x0f
  masked = b1 & 0x80 != 0
  len    = b1 & 0x7f
  len = io.read(2).unpack1('n')  if len == 126 # 16-bit length
  len = io.read(8).unpack1('Q>') if len == 127 # 64-bit length
  mask = masked ? io.read(4).bytes : [0, 0, 0, 0]
  data = io.read(len).bytes.each_with_index.map { |b, i| b ^ mask[i % 4] }
  [opcode, data.pack('C*')]
end

# Write one unmasked, unfragmented frame (servers never mask)
def write_frame(io, opcode, payload)
  payload = payload.b
  header = [0x80 | opcode].pack('C') # FIN bit + opcode
  header << if payload.bytesize < 126
              [payload.bytesize].pack('C')
            elsif payload.bytesize < 65_536
              [126, payload.bytesize].pack('Cn')
            else
              [127, payload.bytesize].pack('CQ>')
            end
  io.write(header, payload)
end

port = Integer(ENV.fetch('PORT', 9292))
server = TCPServer.new('127.0.0.1', port)
puts "listening on ws://127.0.0.1:#{port}/"

client = server.accept

# 1. The opening handshake is plain HTTP/1.1
request_line = client.gets
headers = {}
while (line = client.gets) != "\r\n"
  name, value = line.split(': ', 2)
  headers[name.downcase] = value.strip
end
puts request_line
p headers.slice('upgrade', 'connection', 'sec-websocket-version')

accept = [Digest::SHA1.digest(headers['sec-websocket-key'] + GUID)].pack('m0')
client.write "HTTP/1.1 101 Switching Protocols\r\n" \
             "Upgrade: websocket\r\n" \
             "Connection: Upgrade\r\n" \
             "Sec-WebSocket-Accept: #{accept}\r\n\r\n"

# 2. From now on the socket carries frames
loop do
  opcode, payload = read_frame(client)
  case opcode
  when 0x1 # text
    text = payload.force_encoding('UTF-8')
    puts "got text: #{text}"
    write_frame(client, 0x1, "echo: #{text}")
  when 0x9 # ping -> answer with a pong carrying the same data
    write_frame(client, 0xA, payload)
  when 0x8 # close -> echo the close frame back, then hang up
    code = payload.unpack1('n')
    puts "got close: #{code}"
    write_frame(client, 0x8, payload)
    break
  end
end
client.close
server.close

To talk to it, use the async-websocket client. write sends a UTF-8 String as a text frame, read returns the next complete message:

# raw_client.rb
require 'async'
require 'async/http/endpoint'
require 'async/websocket/client'

Warning[:experimental] = false
port = ENV.fetch('PORT', 9292)
endpoint = Async::HTTP::Endpoint.parse("http://127.0.0.1:#{port}/")

Async do
  Async::WebSocket::Client.connect(endpoint) do |connection|
    connection.write('hello')
    connection.write('zażółć')
    connection.send_ping('ping data')
    connection.flush
    2.times { puts connection.read.buffer }
  end # leaving the block sends a close frame with code 1000
end

Run ruby raw_server.rb in one terminal and ruby raw_client.rb in another. The client prints:

echo: hello
echo: zażółć

and the server prints:

listening on ws://127.0.0.1:9292/
GET / HTTP/1.1
{"upgrade" => "websocket", "connection" => "upgrade", "sec-websocket-version" => "13"}
got text: hello
got text: zażółć
got close: 1000

The client uses an http:// URL because the handshake is HTTP. ws:// and wss:// (WebSocket over TLS) work too.

The hand-written server skips a lot: fragmented messages (continuation frames), checking that text is valid UTF-8, limits on frame size, many clients at once, compression and TLS. Use a library for real code.

An echo server with async-websocket

Async::WebSocket::Adapters::HTTP.open(request) checks whether the request is a WebSocket upgrade. If it is, it completes the handshake, runs the block with the connection in its own fiber, and returns the 101 response. If not, it returns nil, so || can serve a normal HTTP response instead.

The server and a client run in the same script here, so it's easy to try out:

require 'socket'
require 'async'
require 'async/http/server'
require 'async/http/endpoint'
require 'async/websocket/client'
require 'async/websocket/adapters/http'
require 'protocol/http/response'

Warning[:experimental] = false

# Handler: upgrade WebSocket requests, answer everything else with 404
app = lambda do |request|
  Async::WebSocket::Adapters::HTTP.open(request) do |connection|
    puts "server: client connected"
    while (message = connection.read) # nil when the client closes
      puts "server: got #{message.buffer.inspect}"
      connection.write("echo: #{message.buffer}")
      connection.flush
    end
    puts "server: client left"
  end || Protocol::HTTP::Response[404, {}, ["Not a WebSocket request\n"]]
end

port = TCPServer.open('127.0.0.1', 0) { |s| s.addr[1] } # pick a free port
endpoint = Async::HTTP::Endpoint.parse("http://127.0.0.1:#{port}/chat")

Async do |task|
  server_task = task.async { Async::HTTP::Server.new(app, endpoint).run }

  Async::WebSocket::Client.connect(endpoint) do |connection|
    %w[hello world].each do |text|
      connection.write(text)
      connection.flush
      puts "client: #{connection.read.buffer}"
    end
  end

  sleep 0.1
  server_task.stop
end
server: client connected
server: got "hello"
client: echo: hello
server: got "world"
client: echo: world
server: client left

Things to know about the connection API:

A chat room: broadcasting JSON

Most WebSocket apps exchange JSON. TextMessage.generate(hash) encodes a value as JSON, and message.parse decodes it into a Hash with Symbol keys.

To broadcast, keep a collection of open connections. All connections in one Async reactor run as fibers on a single thread, so a plain Set is safe without a Mutex:

require 'socket'
require 'uri'
require 'async'
require 'async/http/server'
require 'async/http/endpoint'
require 'async/websocket/client'
require 'async/websocket/adapters/http'
require 'protocol/http/response'

Warning[:experimental] = false

Message = Protocol::WebSocket::TextMessage

class ChatRoom
  def initialize
    @connections = Set.new # all fibers run on one thread: no Mutex needed
  end

  def join(connection, name)
    @connections << connection
    broadcast(type: 'system', text: "#{name} joined (#{@connections.size} online)")
  end

  def leave(connection, name)
    @connections.delete(connection)
    broadcast(type: 'system', text: "#{name} left")
  end

  def broadcast(payload)
    message = Message.generate(payload) # JSON-encodes the Hash
    @connections.each do |conn|
      message.send(conn)
      conn.flush
    rescue => e # one dead peer must not break the loop for everyone else
      warn "drop #{conn.inspect}: #{e.class}"
      @connections.delete(conn)
    end
  end
end

room = ChatRoom.new

app = lambda do |request|
  Async::WebSocket::Adapters::HTTP.open(request) do |connection|
    query = URI(request.path).query.to_s
    name = URI.decode_www_form(query).to_h.fetch('name', 'anonymous')
    room.join(connection, name)
    while (message = connection.read)
      data = message.parse # JSON -> Hash with Symbol keys
      room.broadcast(type: 'chat', from: name, text: data[:text])
    end
  ensure
    room.leave(connection, name)
  end || Protocol::HTTP::Response[404, {}, ["Not found\n"]]
end

port = TCPServer.open('127.0.0.1', 0) { |s| s.addr[1] }
base = "http://127.0.0.1:#{port}"

Async do |task|
  server = task.async { Async::HTTP::Server.new(app, Async::HTTP::Endpoint.parse(base)).run }

  # Each client runs in its own fiber and prints everything it receives
  client = lambda do |name, lines|
    endpoint = Async::HTTP::Endpoint.parse("#{base}/chat?name=#{name}")
    Async::WebSocket::Client.connect(endpoint) do |conn|
      reader = task.async do
        while (msg = conn.read)
          puts "[#{name}] #{msg.parse}"
        end
      end
      lines.each do |text|
        sleep 0.05
        Message.generate(text: text).send(conn)
        conn.flush
      end
      sleep 0.1
      reader.stop
    end
  end

  alice = task.async { client.call('alice', ['hi bob']) }
  sleep 0.02
  bob = task.async { client.call('bob', ['hello alice']) }
  [alice, bob].each(&:wait)

  server.stop
end
[alice] {type: "system", text: "alice joined (1 online)"}
[alice] {type: "system", text: "bob joined (2 online)"}
[bob] {type: "system", text: "bob joined (2 online)"}
[alice] {type: "chat", from: "alice", text: "hi bob"}
[bob] {type: "chat", from: "alice", text: "hi bob"}
[alice] {type: "chat", from: "bob", text: "hello alice"}
[bob] {type: "chat", from: "bob", text: "hello alice"}
[bob] {type: "system", text: "alice left"}

Note the pattern on the client: one fiber reads in a loop while the main fiber writes. A WebSocket is full duplex, so reading and writing must not block each other.

The ensure in the handler runs however the connection ends (clean close, error, network drop), so the room never keeps dead connections.

The set of connections lives in one process. With several server processes or machines, each process only sees its own clients. The usual fix is a message bus: every process subscribes to a Redis (or PostgreSQL LISTEN/NOTIFY) channel and forwards what it receives to its local connections.

Text, binary, ping and close codes

The message type is picked from the String's encoding: a UTF-8 String is sent as text, a binary (ASCII-8BIT) String is sent as binary. You can also build the message objects yourself.

To see control frames, subclass Async::WebSocket::Connection and pass it as handler::

require 'socket'
require 'async'
require 'async/http/server'
require 'async/http/endpoint'
require 'async/websocket/client'
require 'async/websocket/adapters/http'
require 'protocol/http/response'

Warning[:experimental] = false
WS = Protocol::WebSocket

# A connection subclass that logs control frames
class LoggingConnection < Async::WebSocket::Connection
  def receive_ping(frame)
    puts "server: ping #{frame.unpack.inspect}"
    super # replies with a pong
  end
end

class PongLogger < Async::WebSocket::Connection
  def receive_pong(frame)
    puts "client: pong #{frame.unpack.inspect}"
  end
end

app = lambda do |request|
  next Protocol::HTTP::Response[404, {}, ["Not found\n"]] unless request.path == '/ws'

  Async::WebSocket::Adapters::HTTP.open(request, handler: LoggingConnection) do |conn|
    while (message = conn.read)
      case message
      when WS::BinaryMessage
        puts "server: #{message.size} binary bytes #{message.buffer.unpack('C*').inspect}"
      when WS::TextMessage
        if message.buffer == 'bye'
          conn.close(WS::Error::POLICY_VIOLATION, 'no goodbyes allowed')
          break
        end
        puts "server: text #{message.buffer.inspect} (#{message.buffer.encoding})"
      end
    end
  end
end

port = TCPServer.open('127.0.0.1', 0) { |s| s.addr[1] }
endpoint = Async::HTTP::Endpoint.parse("http://127.0.0.1:#{port}/ws")

Async do |task|
  server = task.async { Async::HTTP::Server.new(app, endpoint).run }

  Async::WebSocket::Client.connect(endpoint, handler: PongLogger) do |conn|
    conn.write('zażółć')                         # UTF-8 String -> text frame
    conn.write("\x01\x02\xff".b)                 # binary String -> binary frame
    WS::BinaryMessage.new("\x00\x2a").send(conn) # explicit message type
    conn.send_ping('are you there?')
    conn.write('bye')
    conn.flush

    begin
      conn.read # processes the pong, then gets the close frame
    rescue WS::ClosedError => e
      puts "client: closed by server, code=#{e.code} reason=#{e.message.inspect}"
    end
  end

  # The server refuses the upgrade for other paths
  begin
    wrong = Async::HTTP::Endpoint.parse("http://127.0.0.1:#{port}/nope")
    Async::WebSocket::Client.connect(wrong) { }
  rescue Async::WebSocket::ConnectionError => e
    puts "#{e.class}: #{e.message}"
  end

  server.stop
end
server: text "zażółć" (UTF-8)
server: 3 binary bytes [1, 2, 255]
server: 2 binary bytes [0, 42]
server: ping "are you there?"
client: pong "are you there?"
client: closed by server, code=1008 reason="no goodbyes allowed"
Async::WebSocket::ConnectionError: Failed to negotiate connection!

A close frame carries a 2-byte status code and an optional reason (at most 123 bytes). Protocol::WebSocket::Error has constants for the common ones:

Code Constant Meaning
1000 NO_ERROR normal close
1001 GOING_AWAY server shutting down, or browser leaving the page
1002 PROTOCOL_ERROR malformed frame
1003 INVALID_DATA a type of data the endpoint can't accept
1007 INVALID_PAYLOAD e.g. a text frame that isn't valid UTF-8
1008 POLICY_VIOLATION generic "you're not allowed"
1009 MESSAGE_TOO_LARGE message over the size limit
1011 INTERNAL_ERROR unexpected server error

Codes 4000-4999 are free for your application, for example 4001 for "token expired".

Heartbeats and idle timeouts

A WebSocket connection can sit idle for hours. Proxies, load balancers and NAT routers often drop connections with no traffic after 30-120 seconds, and a client that lost its network (laptop lid closed) doesn't send a close frame, so the server never learns it's gone.

The fix is a heartbeat: ping every N seconds, and close connections that have been silent for too long. A separate fiber does this while the main fiber reads.

Don't wrap read in task.with_timeout: when the timeout interrupts it, the connection is closed with 1002 PROTOCOL_ERROR. Track the time of the last message instead:

require 'socket'
require 'async'
require 'async/http/server'
require 'async/http/endpoint'
require 'async/websocket/client'
require 'async/websocket/adapters/http'

Warning[:experimental] = false
WS = Protocol::WebSocket

PING_EVERY   = 0.2 # use 20-30 seconds in production
IDLE_TIMEOUT = 0.5 # close if the client sends nothing for this long

def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)

app = lambda do |request|
  Async::WebSocket::Adapters::HTTP.open(request) do |conn|
    last_seen = now

    # A watchdog fiber: pings keep proxies from dropping a quiet connection
    # (and writing to a dead peer raises); silent clients get closed.
    watchdog = Async do
      loop do
        sleep PING_EVERY
        if now - last_seen > IDLE_TIMEOUT
          puts "server: idle for more than #{IDLE_TIMEOUT}s, closing"
          conn.close(WS::Error::GOING_AWAY, 'idle timeout')
          break
        end
        conn.send_ping
        conn.flush
      end
    end

    while (message = conn.read)
      last_seen = now
      puts "server: #{message.buffer}"
    end
  rescue IOError, WS::Error, Errno::ECONNRESET
    # the watchdog closed the socket under the reader, or the peer vanished
  ensure
    watchdog&.stop
  end
end

# Counts pings; super sends the pong
class PingCounter < Async::WebSocket::Connection
  attr_reader :pings

  def receive_ping(frame)
    @pings = (@pings || 0) + 1
    super
  end
end

port = TCPServer.open('127.0.0.1', 0) { |s| s.addr[1] }
endpoint = Async::HTTP::Endpoint.parse("http://127.0.0.1:#{port}/")

Async do |task|
  server = task.async { Async::HTTP::Server.new(app, endpoint).run }

  Async::WebSocket::Client.connect(endpoint, handler: PingCounter) do |conn|
    conn.write('one message, then silence')
    conn.flush
    conn.read
  rescue WS::ClosedError => e
    puts "client: closed code=#{e.code} reason=#{e.message.inspect} after #{conn.pings} pings"
  end

  server.stop
end
server: one message, then silence
server: idle for more than 0.5s, closing
client: closed code=1001 reason="idle timeout" after 2 pings

Pongs answer pings but don't count as messages here, so this client is closed even though its pongs keep arriving. Whether a pong should count as activity depends on what you want: "the client is alive" (override receive_pong to update last_seen) or "the client is doing something".

Browsers answer pings automatically but JavaScript can't send them. If the browser side needs to detect a dead server, send small application-level heartbeat messages such as {"type":"ping"}.

A browser client

Browsers have a built-in WebSocket class. This server serves an HTML page on / and a WebSocket on /ws that sends a few JSON ticks and then closes:

# server.rb
require 'async'
require 'async/http/server'
require 'async/http/endpoint'
require 'async/websocket/adapters/http'
require 'protocol/http/response'

Warning[:experimental] = false

PORT = Integer(ENV.fetch('PORT', 9292))
ALLOWED_ORIGINS = ["http://localhost:#{PORT}", "http://127.0.0.1:#{PORT}"]

PAGE = <<~HTML
  <!doctype html>
  <title>Ticker</title>
  <pre id="log"></pre>
  <script>
    const log = (s) => document.getElementById('log').textContent += s + '\\n';
    const ws = new WebSocket(`ws://${location.host}/ws`);
    ws.onopen    = () => ws.send(JSON.stringify({ subscribe: 'ticks', count: 3 }));
    ws.onmessage = (e) => log(e.data);
    ws.onclose   = (e) => log(`closed: ${e.code} ${e.reason}`);
  </script>
HTML

app = lambda do |request|
  case request.path
  when '/'
    Protocol::HTTP::Response[200, { 'content-type' => 'text/html' }, [PAGE]]
  when '/ws'
    # Browsers always send Origin: reject pages from other sites
    origin = request.headers['origin']
    if origin && !ALLOWED_ORIGINS.include?(origin)
      next Protocol::HTTP::Response[403, {}, ["Forbidden origin\n"]]
    end

    Async::WebSocket::Adapters::HTTP.open(request) do |conn|
      req = conn.read.parse
      req[:count].times do |i|
        tick = { tick: i + 1, at: Time.now.utc.strftime('%T') }
        Protocol::WebSocket::TextMessage.generate(tick).send(conn)
        conn.flush
        sleep 0.1
      end
      conn.close(1000, 'done')
    end || Protocol::HTTP::Response[426, { 'upgrade' => 'websocket' }, ["Upgrade required\n"]]
  else
    Protocol::HTTP::Response[404, {}, ["Not found\n"]]
  end
end

endpoint = Async::HTTP::Endpoint.parse("http://127.0.0.1:#{PORT}")
puts "Open http://127.0.0.1:#{PORT}/ in a browser"
Async { Async::HTTP::Server.new(app, endpoint).run }

Open the page in a browser and it shows:

{"tick":1,"at":"20:22:22"}
{"tick":2,"at":"20:22:22"}
{"tick":3,"at":"20:22:23"}
closed: 1000 done

Node.js 22+ has the same WebSocket class, which is handy for testing a server from the command line. This prints the same lines as the browser:

// client.mjs - run with: node client.mjs
const ws = new WebSocket(`ws://127.0.0.1:${process.env.PORT ?? 9292}/ws`);
ws.onopen    = () => ws.send(JSON.stringify({ subscribe: 'ticks', count: 3 }));
ws.onmessage = (e) => console.log(e.data);
ws.onclose   = (e) => console.log(`closed: ${e.code} ${e.reason}`);

You can also check the server's answers to non-WebSocket requests with curl:

$ curl -i http://127.0.0.1:9292/ws
HTTP/1.1 426 Upgrade Required
upgrade: websocket
...
$ curl -i -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Sec-WebSocket-Version: 13" \
       -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" -H "Origin: https://evil.example" \
       http://127.0.0.1:9292/ws
HTTP/1.1 403 Forbidden
...

Security

Running a Rack app on Falcon

The examples above use Async::HTTP::Server directly. For a deployable app, write a Rack application and run it on Falcon, the fiber-based server from the same family of gems. Async::WebSocket::Adapters::Rack.open(env) works like the HTTP adapter but takes the Rack env and returns a Rack response (see HTTP middleware for more about Rack):

# config.ru
require 'async/websocket/adapters/rack'

Warning[:experimental] = false

class App
  def call(env)
    Async::WebSocket::Adapters::Rack.open(env, protocols: ['json']) do |connection|
      connection.write("welcome, protocol=#{connection.protocol.inspect}")
      connection.flush
      while (message = connection.read)
        connection.write(message.buffer.upcase)
        connection.flush
      end
    end or [200, { 'content-type' => 'text/plain' }, ["Plain HTTP request to #{env['PATH_INFO']}\n"]]
  end
end

run App.new

Start it with:

falcon serve --bind http://localhost:9292

protocols: lists the subprotocols the server supports. The client asks for one or more in the Sec-WebSocket-Protocol header (in JavaScript: new WebSocket(url, ['json'])) and the server picks the first match.

falcon serve uses a process/thread container that relies on Unix signals, so on Windows run the server in-process instead. The same snippet is also a quick way to test the app:

require 'socket'
require 'async'
require 'async/http/endpoint'
require 'async/http/internet'
require 'async/websocket/client'
require 'falcon/server'
require 'rack/builder'

Warning[:experimental] = false

app = Rack::Builder.parse_file('config.ru')
port = TCPServer.open('127.0.0.1', 0) { |s| s.addr[1] }
endpoint = Async::HTTP::Endpoint.parse("http://127.0.0.1:#{port}/live")

Async do |task|
  server = task.async { Falcon::Server.new(Falcon::Server.rack_middleware(app), endpoint).run }

  Async::WebSocket::Client.connect(endpoint, protocols: ['json']) do |conn|
    puts conn.read.buffer
    conn.write('shout this')
    conn.flush
    puts conn.read.buffer
  end

  internet = Async::HTTP::Internet.new
  puts internet.get("http://127.0.0.1:#{port}/about").read
  internet.close
  server.stop
end
welcome, protocol="json"
SHOUT THIS
Plain HTTP request to /about

A WebSocket connection holds its handler for as long as it is open. That fits Falcon, where each connection is a cheap fiber. On a thread-pool server such as Puma, every open WebSocket would take up a thread, which is why Puma-based stacks hand the socket off to a separate event loop (this is what Rails' Action Cable does).

Other options

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents