Sha256: 2cacd6904def943d445c5a0dff639f52e8e59a457d3a1615f8e82b1be2dfdc29

Contents?: true

Size: 1.08 KB

Versions: 3

Compression:

Stored size: 1.08 KB

Contents

# frozen_string_literal: true

require "socket"
require "ipaddr"

module HTTPX
  class UDP
    include Loggable

    attr_reader :ip, :port

    def initialize(ip, port)
      @ip = ip.to_s
      @port = port
      @io = UDPSocket.new(ip.family)
      @closed = false
    end

    def to_io
      @io.to_io
    end

    if RUBY_VERSION < "2.3"
      def read(size, buffer)
        data, _ = @io.recvfrom_nonblock(size)
        buffer.replace(data)
        buffer.bytesize
      rescue ::IO::WaitReadable
        0
      rescue EOFError
        nil
      end
    else
      def read(size, buffer)
        @io.recvfrom_nonblock(size, 0, buffer, exception: false)
        buffer.bytesize
      rescue ::IO::WaitReadable
        0
      rescue EOFError
        nil
      end
    end

    def write(buffer)
      siz = @io.send(buffer, 0, @ip, @port)
      buffer.slice!(0, siz)
      siz
    end

    def close
      return if @closed
      @io.close
    ensure
      @closed = true
    end

    def closed?
      @closed
    end

    def inspect
      "#<(fd: #{@io.fileno}): #{@ip}:#{@port})>"
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
httpx-0.0.5 lib/httpx/io/udp.rb
httpx-0.0.4 lib/httpx/io/udp.rb
httpx-0.0.3 lib/httpx/io/udp.rb