开发者

Ruby Tcp Server class with non-blocking or multithread functionality

Can't find any gem or class which can help to made a non-blocking/multit开发者_JAVA百科hread server. Where to find any?


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


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


Use Celluloid::IO

This is the primary purpose of Celluloid::IO and it is extremely good at what it does:

  • https://github.com/celluloid/celluloid-io

A few example servers...

  • https://github.com/celluloid/celluloid-dns
  • https://github.com/celluloid/reel
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜