I need to send data across to the socket, basically transferring a file ,
According to send() function docs, it says,
If no error occurs, send returns the total number of bytes sent, which can be less than the number requested to be sent in the len parameter. Otherwise, a value of SOCKET_ERROR is returned,
The line that I am worried about is, the return value may be less than requested value. Because I am reading from a file and writing to a socket, because it may not send all the bytes, I guess I would have to retry if the full buffer was not sent ? in which case I guess I would have to somehow advance the pointer on the same buffer by bytes read and send it again ??
I just want know if that's the way about it ? or is there a much clever way to it, so that all the requested data gets sent without me having to worry about when not all data was sent ?
Thanks,
The send() function shall initiate transmission of a message from the specified socket to its peer. The send() function shall send a message only when the socket is connected (including when the peer of a connectionless socket has been set via connect()).
The simplest answer is that the data is an uninterpreted stream of octets, that is to say 8-bit bytes. Any interepretation of it is done by the sender and receiver, and they better agree.
Create a Socket client. With the endPoint object created, create a client socket to connect to the server. Once the socket is connected, it can send and receive data from the server socket connection. using Socket client = new( ipEndPoint.
Create a socket with the socket() system call. Initialize the socket address structure as per the server and connect the socket to the address of the server using the connect() system call. Receive and send the data using the recv() and send(). Close the connection by calling the close() function.
Yes, you have to advance the buffer pointer and repeat the send
call until either the entire buffer is consumed or you get a hard error. The standard idiom looks something like this:
int
send_all(int socket, const void *buffer, size_t length, int flags)
{
ssize_t n;
const char *p = buffer;
while (length > 0)
{
n = send(socket, p, length, flags);
if (n <= 0)
return -1;
p += n;
length -= n;
}
return 0;
}
Note that if you are sending datagrams whose boundaries matter (e.g. UDP) you cannot use this technique; you have to treat a short send as a failure.
You could try something like:
int ret, bytes = 0;
while (bytes < buflen) {
ret = send(sock_fd, buf+bytes, buflen-bytes, flags);
//check for errors
if (ret == -1) {
// handle error
}
bytes+=ret;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With