Ruby Tcp Server class with non-blocking or multi-threaded functionality

It is not possible to find any stone or class that can help create a non-blocking / multithreaded server. Where to find?

+3
source share
3 answers

Ruby docs on sockets have some good examples. Using the information from this page, I combined a simple client and server using non-blocking sockets. These are basically copies of the code from this page with a few changes.

Simple server code (with a call accept_nonblockthat may interest you):

 require 'socket'
 include Socket::Constants


 socket = Socket.new(AF_INET, SOCK_STREAM, 0)
 sockaddr = Socket.sockaddr_in(6212, 'localhost')
 socket.bind(sockaddr)
 socket.listen(5)
 begin
   client_socket, client_sockaddr = socket.accept_nonblock
 rescue Errno::EAGAIN, Errno::ECONNABORTED, Errno::EINTR, Errno::EWOULDBLOCK
   IO.select([socket])
   retry
 end
 puts client_socket.readline.chomp
 client_socket.puts "hi from the server"
 client_socket.close
 socket.close

And the client who speaks with him:

 require 'socket'
 include Socket::Constants

 socket = Socket.new(AF_INET, SOCK_STREAM, 0)
 sockaddr = Socket.sockaddr_in(6212, 'localhost')
 begin
   socket.connect_nonblock(sockaddr)
 rescue Errno::EINPROGRESS
   IO.select(nil, [socket])
   begin
     socket.connect_nonblock(sockaddr)
   rescue Errno::EINVAL
     retry
   rescue Errno::EISCONN
   end
 end
 socket.write("hi from the client\n")
 results = socket.read
 puts results
 socket.close
+6
source

EventMachine. :

require "rubygems"
require "eventmachine"

module EchoServer
  def receive_data (data)
    send_data "You said: #{data}"
  end
end

EventMachine::run do
  EventMachine::start_server "0.0.0.0", 5000, EchoServer
end
+5

Source: https://habr.com/ru/post/1730811/


All Articles