0

我对 TCP 套接字上的 send() 有疑问。

有没有区别:

char *text="Hello world";
char buffer[150];

for(i=0;i<10;i++)
    send(fd_client, text, strlen(text) );

char *text="Hello world";
char buffer[150];

buffer[0]='\0';
for(i=0;i<10;i++)
    strcat(buffer, text);

send(fd_client, buffer, strlen(buffer) );

接收端使用recv有区别吗?两者都将成为一个 TCP 数据包吗?

即使设置了 TCP_NODELAY?

4

2 回答 2

0

TCP is stream based protocol. If you run Send, it will put some data into OS TCP layer buffer and OS will send it periodically. But if you call Send too quick it might put few arrays into OS TCP layer before the previous one were sent. So it is like stack, it sends whatever it has and put everything in one big array.
Sending is btw done with segmentation by OS TCP layer, and there is as well Nagle's algorithm that will prevent sending small amount data before OS buffer will be big enough to satisfy one segment size.

So yes, there is difference.

TCP is stream based protocol, you can't rely on that single send will be single receive with same amount of data.
Data might merge together and you have to remember about that all the time.

Btw, based on your examples, in first case client will receive all bytes together or nothing. In meantime if sending one big segment will drop somewhere on the way then server OS will automatically resend it. Drop chance for bigger packets is higher so and resending of big segments will lead to some traffic lose. But this is based on percentage of dropped packets and might be not actual for your case at all.

In second example you might receive everything together or parts each separate or some merged. You never know and should implement you network reading that way, that you know how many bytes you expecting to receive and read just that amount of bytes. That way even if there is left some unread bytes they will be read on next "Read".

于 2012-04-25T13:05:26.213 回答
0

实在没有办法知道。取决于 TCP 的实现。如果是 UDP 套接字,它们肯定会有不同的结果,在第一种情况下你会有几个数据包,在第二种情况下会有一个数据包。

TCP 可以随意拆分数据包;它模拟一个流并将它的数据包机制从用户那里抽象出来。这是设计使然。

于 2012-04-25T12:41:05.543 回答