使用TCPSocket
,我需要socket.puts "foobar"
,然后socket.close
让套接字在对方socket.read
的消息。
有没有办法通过套接字发送或接收消息,但不关闭套接字,这意味着我可以再次发送消息而无需再次创建套接字?
ps 类似 websocket 的东西
If you traverse up the super class chain you will eventually see that you inherit from IO
. Most IO
objects, in Ruby, buffer the data to be more efficient writing and reading from disk.
In your case, the buffer wasn't large enough (or enough time didn't pass) for it to flush out. However, when you closed the socket, this forced a flush of the buffer resources.
You have a few options:
IO#flush
.IO#sync=
to true
. You can check the status of your IO
object's syncing using IO#sync
; I'm guessing you'd see socket.sync #=> false
BasicSocket#send
which will call POSIX send(2)
; since sockets are initialized with O_FSYNC
set, the send will be synchronous and atomic.不必关闭连接以便对方读取它。send
应立即通过连接传输数据。确保对方正在从套接字读取。