简体   繁体   中英

recv function for TCP socket in C++

I am new in socket programming. I have a client application written in c++ that connect to camera. And then Camera sends the packet of frames in chunks between 0 - 1460. I have used recv function to receive the packet. I saw soo many question in which it was clearly mentionthat recv function return the bytes received, but in my case recv function returning the value written in the 3rd parameter of the recv function ie len. So is their anyway through whichI can find the actual bytes received.

I even try to use char* but that not even work.

So, anyone please tell me the solution.Any help will be appreciable. Thank in Advance

char *buf = new char[1461];
int bytes = recv(sock, buf, 2000, 0);
printf("%d", bytes);

that always print 2000. because of that after the valid bytes in the buf their are unknown bytes that's results in unexpected Image.

First of all, your code has a bug (which leads to undefined behavior). You have allocated 1461 bytes but you are trying to read more than that:

It should go like this:

vector<char> buf(5000); // you are using C++ not C
int bytes = recv(sock, buf.data(), buf.size(), 0);
std::cout << bytes;

Secondly result is as expected. Camera sends much more data than 2000 bytes, so I'm not surprised that number of bytes read covers whole requested size.

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