Ruby TCPSocket write does not work, but puts does?

I am working on a Ruby TCP client / server application using GServer and TCPSocket. I ran into a problem that I do not understand. My TCPSocket client successfully connects to my GServer server, but I can only send data using puts. Calls to TCPSocket.send or TCPSocket.write do nothing. Is there any magic I'm missing?

tcp_client = TCPSocket.new( ipaddr, port ) tcp_client.puts( 'Z' ) # -> GServer receives "Z\n" 

But if I use write or send ...

 tcp_client = TCPSocket.new( ipaddr, port ) tcp_client.write( 'Z' ) # -> nothing is received tcp_client.send( 'Z' ) # -> nothing is received 

thanks for the help

Additional Information:

  • The behavior is the same for Linux and Windows.
  • Flushing the socket after recording does not change the behavior.
+6
ruby sockets tcp
source share
5 answers

Are you sure the problem is not server side? Are you using some kind of reading method that expects a string or something that ends with "\ n"?

+4
source share

With buffering, which was taken care of in previous posts, to solve the question of whether data is being sent, consider capturing data in a string using wireshark . If the data you send is visible on the line, then the server does not receive it.

Otherwise, if the data does not go to the string, TCP may contain data to avoid sending one segment with several bytes in it ( see the Nagle algorithm ). Depending on your OS or TCP provider, you may have different behavior, but most TCP stacks support the TCP_NODELAY parameter, which can help you receive data more timely.

 tcp_client.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) 

This can help debugging, but as a rule, it cannot be left in production code if bandwidth has a higher priority than responsiveness.

+3
source share

Try to rinse explicitly:

 tcp_client = TCPSocket.new( ipaddr, port ) tcp_client.write( 'Z' ) tcp_client.send( 'Z' ) tcp_client.flush 

In this way, the output is buffered maximum until the point at which you decide is to be sent.

+2
source share

Hi, the reason should be related to the addition of automatic LF and CRL to your string. If you want to use sending or recording, you need to add them yourself, for example, for example:

tcp_client.send ("Z \ r \ n", 0)

0
source share

I had the same problem, so after reading the socket, I had to explicitly delete the last instance of "\ n" by doing the following:

 client_socket.gets.gsub(/\n$/, '') 
0
source share

All Articles