gpt4 book ai didi

ruby-on-rails - TCP 套接字 IO 卡住

转载 作者:太空宇宙 更新时间:2023-11-03 16:48:59 25 4
gpt4 key购买 nike

我想实现一个 TCP 客户端并使用一个线程来读取另一个要写的线程。但是对于读取线程,我遇到了一个问题:“stuck while io gets bytes”

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

谁能帮忙解决这个问题?

最佳答案

使用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

关于ruby-on-rails - TCP 套接字 IO 卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27360637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com