0

使用TCPSocket,我需要socket.puts "foobar",然后socket.close让套接字在对方socket.read 的消息。

有没有办法通过套接字发送或接收消息,但不关闭套接字,这意味着我可以再次发送消息而无需再次创建套接字?

ps 类似 websocket 的东西

4

2 回答 2

3

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:

  • You can manually force the buffer to flush using IO#flush.
  • You can set the buffer to always sync after a write / read, by setting 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
  • Use BasicSocket#send which will call POSIX send(2); since sockets are initialized with O_FSYNC set, the send will be synchronous and atomic.
于 2013-05-05T14:44:46.913 回答
1

不必关闭连接以便对方读取它。send应立即通过连接传输数据。确保对方正在从套接字读取。

于 2013-05-05T11:04:52.817 回答