How to maintain the TCP connection using Ruby?

2019-08-29 07:53发布

问题:

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.