Sha256: 6e55e6607b4867d9fc6335172b5c23ebcfafbb9006dc5358d3276d0de647e9fb

Contents?: true

Size: 1.19 KB

Versions: 1

Compression:

Stored size: 1.19 KB

Contents

require 'celluloid'
require 'celluloid/notifications'
require 'socket'

module Hokaido
  class ConnectionHandler
    include Celluloid
    include Celluloid::Notifications

    def initialize(connection)
      @connection = connection

      async.run
    end

    def run
      _, port, host = @connection.peeraddr

      puts "#{host}:#{port} connected"

      case @connection.gets.chomp
      when 'broadcast'
        @connection.puts ':)'

        while chunk = @connection.readpartial(4096)
          publish 'broadcast', chunk
        end
      when 'watch'
        @connection.puts '=)'

        Watcher.new(@connection).link Actor.current

        Kernel.sleep
      else
        @connection.puts ':('
      end
    rescue EOFError, Errno::EIO, Errno::ECONNRESET
      # do nothing
    ensure
      puts "#{host}:#{port} disconnected"

      @connection.close
    end
  end

  class Server
    include Celluloid

    finalizer :shutdown

    def initialize(host, port)
      @server = TCPServer.new(host, port)

      async.run
    end

    def shutdown
      @server.close if @server
    end

    def run
      loop do
        ConnectionHandler.new(@server.accept).link Actor.current
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hokaido-0.0.7 lib/hokaido/server.rb