filetransfer with socket and tcp
hallo,
i have a little problem with a small server/client program. I have to do it for studies.
the programm should be able to transfer files from server to client. i've tried it in the way below, but it has a bug. When i send the file my client recieves only the first line of the file. But i don't know where the problem is.
here is the important part of the server code
while(1)
{
/* for (i = 0; i < MAXLENGTH; i++)
buf[i]=0;*/
fd2 = accept(fd,(struct sockaddr *)&client, &sin_size);
if(fd2 == -1)
{
printf("accept() errorn");
exit(-1);
}
printf("You got a connection from %s \n",inet_ntoa(client.sin_addr) );
send(fd2,"Welcome to my server\n",22,0); /* send to the client welcome message */
numbytes = recv(fd2, buf, MAXLENGTH, 0);
if (numbytes > 0)
printf("recieved Filename: %s\n", buf);
else
perror("data error");
filetocp = fopen((const char*) buf, "r");
if (filetocp == NULL)
{
perror("opening file failed");
close(fd2);
continue;
}
i=0;
while (fgets(buf, MAXLENGTH, filetocp) != NULL)
{
i++;
printf("%s\n", buf);
printf("sending...\n");
send(fd2,buf,strlen(buf)+1,0); /* sending file */
}
printf("%d\n", i);
printf("sending finished\n");
fclose(filetocp);
close(fd2); /* close fd2 */
}
and now the client code
if ((numbytes=recv(fd,buf,MAXLENGTH,0)) == -1)
{
perror("recv() error");
exit(-1);
}
printf("%s\n", buf);
numbytes = send(fd,filename,strlen(filename)+1,0); /* send to the client welcome message */
if (numbytes == 0)
printf("Error");
else
printf("%d\n", numbytes);
if (numbytes == -1)
{
perror("file recieving failed, perhaps it doesn't exist ");
exit (-1);
}
filetorv = fopen((const char*) filename, "w");
perror("oeffne file");
i=0;
while(recv(fd, buf, MAXLENGTH, 0) > 0)
{
i++;
printf("%d\n", i);
printf("empfange...\n");
fputs(buf, filetorv);
}
if (filetorv != NULL)
{
fclose(filetorv);
perror("schliesse Datei: ");
}
exit(1);
perhaps anybody can help me...
thanks
|