0

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

2 Answers 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.
Sign up to request clarification or add additional context in comments.

3 Comments

One should not have to set sync on sockets. Looking at the source, sockets are initialized with O_FSYNC set and #send just calls POSIX send(2)
Hmmm, overlooked that OP was using puts, not send, that does go through internal buffering logic controlled by sync
Great answer! I've tried all three solution, all works, and thanks for point out the underlying POSIX operation
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.