简体   繁体   English

使用TCP / IP进行套接字编程:recv()块

[英]Socket programming with TCP/IP: recv() blocks

I am developing a simple Client/Server project which moves a chunk of data from client to server. 我正在开发一个简单的客户端/服务器项目,该项目将大量数据从客户端移动到服务器。 I use TCP/IP. 我使用TCP / IP。

The server sets up a listening socket and the client connects. 服务器建立一个监听套接字,客户端建立连接。 First a short 16 byte "header" is transmitted containing some information including the amount of data to be transmitted after. 首先,发送一个短的16字节“报头”,其中包含一些信息,其中包括要发送的数据量。 Afterwards the big chunk is transmitted (around 2MB), namely 之后大块传输(大约2MB),即

send( socketDesc, (void *) myBuffer, bigChunkSize, 0 );

and

recv( socketDescPeer, (void *) myBuffer, bigChunkSize, 0 )

First i implemented the client side under windows using winsock2, which works without problems. 首先,我使用winsock2在Windows下实现了客户端,可以正常工作。 I now tried to port this implementation to linux, in which case the server side never returns from the recv() call (the "header" however is transmitted correctly). 我现在尝试将此实现移植到linux,在这种情况下,服务器端再也不会从recv()调用返回(但是“ header”已正确传输)。 I then tried to send the data in smaller chunks of fixed size like this 然后,我尝试像这样以固定大小的较小块发送数据

unsigned int byteSent = 0;
while( byteSent < bigChunkSize ) {
    int result = send( socketDesc, (void *) myBuffer, smallChunkSize, 0 );
    if ( result < 0 ) {...} else { byteSent += result; }
}

Now, the server receives the first few number of chunks but then again, blocks. 现在,服务器收到前几个块,然后又收到块。

Any ideas? 有任何想法吗? Keep in mind that transmission works without problems using winsock2! 请记住,使用winsock2传输不会出现问题! Thanks a lot! 非常感谢!

Did you check the return code of send to check, how many bytes were really send? 您是否检查了发送检查的返回码,实际发送了多少字节? Neither send nor recv are guaranteed to send/receive the given number of bytes. send和recv都不能保证发送/接收给定的字节数。 They can handle less and you have to call send/recv again to handle the rest. 他们处理的更少,您必须再次致电send / recv来处理其余的事务。

So if you actually send less bytes than expected it explains, why the recv will block waiting for more data (which were not send). 因此,如果实际发送的字节数少于预期的字节数,这说明了为什么recv将阻止等待更多数据(未发送)。

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

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