简体   繁体   中英

Specify packet size with Ruby TCPSocket

I am using Ruby to test a C# networking application, which uses sockets. I open the connection with @socket = TCPSocket.new(IP,PORT) and it works - until the text I want to send is longer than 1024 characters. Then Ruby splits the message into 2 parts. C++ and C# send the message as one packet, so the C# application doesn't need to join the parts.

The messages never get longer than approx. 2000 chars. Is there a possibility to set the packet size for TCPSocket?

EDIT: All of your answers are correct, but after reading a lot of ruby socket questions here on SO I found the solution:

socket.send(msg,0x4)

does not split the message. The option for direct send makes the difference.

I don't know if this works over the internet, but it works in my test lab.

Thx for the help.

TCP is a stream protocol. It does not care about application "messages". TCP can theoretically send your 1024 bytes in one packet, or in 1024 packets. That said, keep in mind that Ethernet MTU is 1500 bytes. Factor in IP header , which is normally 20, and TCP header , which is at least 20. Then your 2000-char message will have to be sent in at least two packets. TCP also does flow control, which might be relevant to the issue. The best way to find out what's going on on the wire is to use tcpdump or wireshark .

The number of packets required to transmit your data should have very little effect on the stream in practice. What you might be encountering is a buffering problem in your implementation.

A socket should only be written to when it's in a "writeable" state, otherwise you risk overflowing the output buffer and causing the connection to be dropped by your networking stack.

As a TCP/IP socket functions as a simple stream, where data goes in, and comes out in order, the effect of packet fragmentation should be mostly irrelevant except for extremely time-sensitive applications.

Make sure you flush your output buffer when writing to the socket or you may have some data left waiting to transmit:

@socket.write(my_data)
@socket.flush

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM