- 论坛徽章:
- 0
|
int sd, bytes_written = 0, retval;
sd = socket(AF_INET, SOCK_STREAM, 0);
... /*** Connect to host ***/
while ( bytes_written < len ) /* repeat sending until all */
{ /*...bytes of message are sent */
retval = write(sd, buffer+bytes_written, len);
if ( retval >= 0 )
bytes_written += retval;
else
/*---report connection error---*/
}
FILE *sp;
int sd;
sd = socket(AF_INET, SOCK_STREAM, 0);
... /*** Connect to host ***/ sp = fdopen(sd, "w"); /* create FILE* from socket */
if ( sp == NULL )
perror("FILE* conversion failed");
fprintf(sp, "%s, %s, %s\ n",Name, Address, Phone);
Note that in the first example, the program has to loop on the write() to get all the bytes out. Even though this is a socket stream, you cannot guarantee that the program sends all the bytes at once. The second instance does not have that limitation, because FILE* has its own data-buffering subsystem. When you write to a FILE* buffer, the subsystem forces you to wait until it sends all the bytes.
黑体部分不太懂, 还望指教 |
|