How to maintain the TCP connection using Ruby?

邮差的信 提交于 2019-12-13 06:22:16

问题


Using TCPSocket, I need to socket.puts "foobar", and then socket.close to let the socket in the other side socket.read the message.

Is there a way to send or receive a message though a socket, but without closing the socket, which mean I can send message again without creating a socket again?

p.s Something like websocket


回答1:


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.



回答2:


It should not be neccessary to close the connection in order for the other party to read it. send should transfer the data over the conection immediately. Make sure the other party is reading from the socket.



来源:https://stackoverflow.com/questions/16383416/how-to-maintain-the-tcp-connection-using-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!