我想实现一个TCP客户端并使用一个线程来读取 写另一个线程。但是对于读取线程,我遇到了一个问题:"卡住而io获取字节"
class SocketClientManager
def initialize
@socket = TCPSocket.new '192.168.3.86', 15533
@response = nil
@send = nil
read
end
def read
@response = Thread.new do
loop {
p "listen response from TCP server"
# will stuck here while trying to "get bytes" from io in the code below
header = @socket.gets(4).unpack('N')[0]
case header
when case1
when case2
end
}
end
end
任何人都可以帮忙解决这个问题吗?
答案 0 :(得分:0)
使用recmsg_nonblock方法可以解决问题。
readfds, writefds, exceptfds = select([@socket], nil, nil, 1)
p :r => readfds, :w => writefds, :e => exceptfds
if readfds
p "we are in read status"
#will not be blocked if not gets bytes from buffer
hhh = @socket.recvmsg_nonblock(10000)
else
p "we are not in read status"
end