Writing send_all and recv_all functions for sockets in C -


I am a new programmer and therefore you will be excited for the lack of knowledge. To send the data back and forth between the client and the server, I am trying to use sockets in C on the Windows machine. I'm using Signbook's tool with CodeBox IDE. Simple send and received was not working and so after some search I was under this impression. My problem was that I needed a send_all and recv_all function I wrote the following two functions but the received always gets stuck in an infinite loop is. I'm not sure why

zero send_all (intel socket, zero * buffer, full length) {size_t i = 0; (I = 0; i & lt; length; i + = send (socket, buffer, length - i, 0)) {printf ("full:% d bytes", i); } Printf ("complete:% d bytes \ n", length); } Zero recovery_ (int sockfid, zero * buffer, int lamp) {size_t i = 0; (I = 0; i & lt; length; i + = recv (sockfd, buffer + i, length - i, 0)) {printf ("full:% d bytes", i); } Printf ("completed:% d bytes \ n", length); }

I am thinking that this is because the recipient does not know how many senders sending the bytes. All advice is appreciated, but please keep it creative thanks.

recv () actually signed value ( int in Winsock, POSIX in ssize_t ). If there is a reading error, or if the socket is in non-intercept mode and no data is available then its return value can be a negative number. Its return value is zero if the socket was closed deeply (this would be the reason for the infinite loop in your code).

Before you can add it to your byte counter, it will have to check the value of returning, to find out both of these situations.

If your socket is in blocking mode (default), your code will block indefinitely until the required data is received or there is an error (once you check the code For that) This is a behavior that is called the name of your function that you want if yes, then your general approach is sound.

  ssize_t bytesRead = 0; While (bytes read length) {ssize_t rv = recv (/ * ... * /); If (RV == 0) {printf ("Socket was closed before closing data \ n"); break; } Else if (rv & lt; 0) {// If your socket is non-blocked, then check for EAGAIN / which means that there is currently no data available; In this case you can do something like // Select a call on the socket () // More data comes in the printf ("Read the error before getting enough data \ n"); break; } Bytes Reid + = RV .; }  

Comments