具有非阻塞或多线程功能的Ruby Tcp Server类

找不到任何可以帮助制作非阻塞/多线程服务器的gem或类.
  哪里可以找到?
最佳答案
套接字上的Ruby docs有一些非常好的例子.使用该页面中的信息,我使用非阻塞套接字拼凑了一个简单的客户端和服务器.这些主要是来自该页面的代码副本,只有一些更改.

简单的服务器代码(带有您可能感兴趣的accept_nonblock调用):

 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

与之交谈的客户:

 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

转载注明原文:具有非阻塞或多线程功能的Ruby Tcp Server类 - 代码日志