简体   繁体   English

使用Ruby TCPSocket指定数据包大小

[英]Specify packet size with Ruby TCPSocket

I am using Ruby to test a C# networking application, which uses sockets. 我正在使用Ruby测试使用套接字的C#网络应用程序。 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. 我用@socket = TCPSocket.new(IP,PORT)打开连接,它可以正常工作-直到我要发送的文本超过1024个字符为止。 Then Ruby splits the message into 2 parts. 然后,Ruby将消息分为两部分。 C++ and C# send the message as one packet, so the C# application doesn't need to join the parts. C ++和C#将消息作为一个数据包发送,因此C#应用程序不需要加入这些部分。

The messages never get longer than approx. 消息永远不会超过大约。 2000 chars. 2000个字符。 Is there a possibility to set the packet size for TCPSocket? 是否可以设置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. 我不知道这是否可以在Internet上使用,但可以在我的测试实验室中使用。

Thx for the help. 谢谢。

TCP is a stream protocol. TCP是流协议。 It does not care about application "messages". 它不关心应用程序的“消息”。 TCP can theoretically send your 1024 bytes in one packet, or in 1024 packets. 理论上,TCP可以在一个数据包或1024个数据包中发送1024字节。 That said, keep in mind that Ethernet MTU is 1500 bytes. 也就是说,请记住以太网MTU为1500字节。 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. IP标头 (通常为20)和TCP标头 (至少为20)中考虑因素。那么您的2000个字符的消息将必须至少以两个数据包发送。 TCP also does flow control, which might be relevant to the issue. TCP还可以进行流量控制,这可能与该问题有关。 The best way to find out what's going on on the wire is to use tcpdump or wireshark . 找出网络上发生了什么的最好方法是使用tcpdumpwireshark

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. 由于TCP / IP套接字的作用就像一个简单的流,数据按顺序传入和传出,因此,数据包分段的影响应该几乎不相关,除了对时间非常敏感的应用程序外。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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