Hello
Can't find any gem or class which can help to made a non-blocking/multithread server. Does anybody know where to find any ?
Hello
Can't find any gem or class which can help to made a non-blocking/multithread server. Does anybody know where to find any ?
Take a look at EventMachine. Here’s a quick example:
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
The Ruby docs on sockets have some pretty good examples. Using information from that page, I cobbled together a simple client and server using non-blocking sockets. These are mostly copies of code from that page with a few changes.
The simple server code (with the accept_nonblock
call that you may be interested in):
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 a client that talks to it:
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