module DirectchatMeshIo
Constants
- DEFAULT_OPEN_TIMEOUT
Public Instance Methods
Source
# File lib/directchat/mesh_io.rb, line 26 def connect(host:, port:, open_timeout: DEFAULT_OPEN_TIMEOUT) socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) sockaddr = Socket.sockaddr_in(port, host) begin socket.connect_nonblock(sockaddr) rescue Errno::EINPROGRESS, IO::WaitWritable unless IO.select(nil, [socket], nil, open_timeout) socket.close raise Errno::ETIMEDOUT, "connect timeout" end begin socket.connect_nonblock(sockaddr) rescue Errno::EISCONN nil end end socket end
Source
# File lib/directchat/mesh_io.rb, line 15 def send_lines(host:, port:, lines:, open_timeout: DEFAULT_OPEN_TIMEOUT) socket = connect(host: host, port: port, open_timeout: open_timeout) Array(lines).each do |line| socket.puts(line.to_s) end socket.close true rescue StandardError false end
Source
# File lib/directchat/mesh_io.rb, line 48 def start_listener(port:, on_line:, on_error: nil) server = TCPServer.new("0.0.0.0", port) thread = Thread.new do loop do client = server.accept Thread.new do client.each_line do |line| on_line.call(line) end rescue StandardError => e on_error&.call(e) ensure client.close unless client.closed? end end rescue StandardError => e on_error&.call(e) end { server: server, thread: thread } end
Source
# File lib/directchat/mesh_io.rb, line 69 def stop_listener(server:, thread:) server&.close thread&.kill end