|
如下是一个简单的client程序,将 127.0.0.1:9000 的数据读入写到/tmp/data.txt中
[php]
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void
error (char *msg)
{
perror (msg);
exit (0);
}
int
main ()
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[4086 * 4086];
portno = atoi ("9000");
sockfd = socket (AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error ("ERROR opening socket");
server = gethostbyname ("127.0.0.1");
if (server == NULL)
{
fprintf (stderr, "ERROR, no such host\n");
exit (0);
}
memset ((char *) &serv_addr, 0, sizeof (serv_addr));
serv_addr.sin_family = AF_INET;
memcpy ((char *) &serv_addr.sin_addr.s_addr, (char *) server->h_addr,
server->h_length);
serv_addr.sin_port = htons (portno);
if (connect (sockfd, &serv_addr, sizeof (serv_addr)) < 0)
error ("ERROR connecting");
memset (buffer, 0, sizeof buffer);
n = read (sockfd, buffer, sizeof (buffer) - 1);
if (n < 0)
error ("ERROR reading from socket");
////////////////////
FILE *fp = fopen ("/tmp/data.txt", "w");
fwrite (buffer, sizeof buffer, 1, fp);
fclose (fp);
}
[/php]
设定产生到 127.0.0.1:9000 的媒体数据流,运行程序,结束后产生1.6M的/tmp/data.txt文件,但只有前3,4行有几k的数据。后面全是0了。为什么读了一会就中断了?client程序应该怎样写? |
|