我需要为TCPSoket
客户端实现一个监听循环,它不会阻止将数据发送到同一个套接字。
近似结构如此:
class SocketWrapper
def initialize
@messages = []
@socket = TCPSocket.open('192.168.0.25', 2000)
Thread.new do
loop do
@messages.push @socket.read
end
end
end
def send_message(msg)
@socket.write msg
end
def read_messages
@messages.dup
@messages.clear
def
end
这个结构一切都好吗?
我需要在这里实施两个策略:
答案 0 :(得分:4)
Ruby有一个专为此设计的课程 - Queue
:
class SocketWrapper
def self.instance
@inst ||= self.new
end
def initialize
@messages = Queue.new
@socket = TCPSocket.open('192.168.0.25', 2000)
Thread.new do
loop do
@messages << @parse_message.nil? ? @socket.read : @parse_message.call(@socket.read)
end
end
end
def parse_message(&block)
@parse_message = block
end
def send_message(msg)
@socket.write msg
end
def read_messages
result = []
begin
while message = @messages.pop(true)
result << message
end
rescue ThreadError
#raised if queue is empty
end
result
def
end
在初始化程序中:
SocketWrapper.instance.parse_message do |raw|
JSON.parse(raw)
# or any other awesome thing with raw
end
在控制器中:
SocketWrapper.instance.send_message('blah blah blah')