Home

Awesome

ruby json-socket .github/workflows/ci.yml

JSON-socket client & server implementation based on async-io. Inspired by and compatible with sebastianseilund/node-json-socket and crystal json-socket

Oj is used for encoding/parsing json.

Installation

gem install json-socket

or in Bundler

gem 'json-socket'

Usage

server.rb

require "json-socket"

class CustomJSONSocketServer < JSONSocket::Server

  def on_message(message, client)
    puts message
    result = message["a"] + message["b"]
    self.send_end_message({ :result => result }, client)
  end

  def on_error e
    STDERR.puts "Error: #{e.message}"
  end
end

server = CustomJSONSocketServer.new(host: "localhost", port: 1234, delimeter: "ц") # OR via unix socket CustomJSONSocketServer.new(unix_socket: "/tmp/s.sock", delimeter: "ц")
server.listen

client.rb

require "json-socket"

to_server = JSONSocket::Client.new(host: "localhost", port: 1234, delimeter: "ц") # OR via unix socket CustomJSONSocketServer.new(unix_socket: "/tmp/s.sock", delimeter: "ц")

10.times do |i|
  result = to_server.send({ "a" => i, "b" => i + 10 })
  p result
end