本文介绍了具有非阻塞或多线程功能的 Ruby Tcp Server 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
找不到任何有助于制作非阻塞/多线程服务器的 gem 或类.在哪里可以找到?
Can't find any gem or class which can help to made a non-blocking/multithread server. Where to find any?
推荐答案
Ruby套接字上的文档 有一些很好的例子.使用来自该页面的信息,我使用非阻塞套接字拼凑了一个简单的客户端和服务器.这些主要是该页面的代码副本,并进行了一些更改.
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.
简单的服务器代码(带有您可能感兴趣的 accept_nonblock
调用):
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
这篇关于具有非阻塞或多线程功能的 Ruby Tcp Server 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!