i need to transfer a file of 8.3MB over TCP, when i use file pointers to read and write to files then i send about 8.6MB data and also receives 8.6 MB of data by calculating the output of send and recv calls although my file size is 8.3 MB, further the when i check the size of file separately by seeing its properties then it is around 3-5 MB (varies on every transfer) but when i use file descriptors in place of file pointers then i send and recv exactly 8.3 MB of data and file property size also shows 8.3 MB. So what is the problem in using file pointers and why is it removed in case of file descriptors.... but if i use file descriptors then i am not able to read the text file that i sent. Text editors shows some binary data in the file. i am not getting a bit of what is happening... please help and thanks in advance
server.cpp
#include "server.h"
void server()
{
int fd = open("out.txt",O_WRONLY);
struct sockaddr_in sin;
socklen_t addr_size;
char buf[MAX_LINE];
int len;
int s, new_s;
/* build address data structure */
bzero((char *) & sin, sizeof (sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(SERVER_PORT);
printf("File Descriptor : %d", fd);
/* setup passive open */
if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("simplex-talk: socket");
exit(1);
}
if ((bind(s, (struct sockaddr *) & sin, sizeof (sin))) < 0)
{
perror("simplex-talk: bind");
exit(1);
}
listen(s, MAX_PENDING);
// wait for connection, then receive and print text */
while (1)
{
if ((new_s = accept(s, (struct sockaddr *) & sin, &addr_size)) < 0)
{
perror("simplex-talk: accept");
exit(1);
}
float total = 0;
printf("File Descriptor : %d", fd);
while (len = recv(new_s, buf, MAX_LINE, 0) && strcmp(buf,"close"))
{
buf[len] = 0;
total = total+len;
//write(stdout, buf, len);
write(fd, buf, len);
//printf("%fKB and %fMB\n",total/1024, total/(1024*1024));
}
printf("File Descriptor : %d", fd);
close(new_s);
}
}
client.cpp
#include "client.h"
void client(int argc, char** argv)
{
int fd = open("/home/nikku/Desktop/data.txt",O_RDONLY);
if (fd < 0 ) perror("File not opened\n");
struct hostent *hp;
struct sockaddr_in sin;
char *host;
char buf[MAX_LINE];
int s;
int len;
host = argv[1];
if (argc == 2)
{
host = argv[1];
}
else
{
fprintf(stderr, "usage: simplex-talk host\n");
exit(1);
}
/* translate host name into peer’s IP address */
gethostname(host,20);
printf("%s\n",host);
hp = gethostbyname(host);
if (!hp)
{
fprintf(stderr, "simplex-talk: unknown host: %s\n", host);
exit(1);
}
/* build address data structure */
bzero((char *) & sin, sizeof (sin));
sin.sin_family = AF_INET;
bcopy(hp->h_addr, (char *) & sin.sin_addr, hp->h_length);
sin.sin_port = htons(SERVER_PORT);
/* active open */
if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("simplex-talk: socket");
exit(1);
}
if (connect(s, (struct sockaddr *) & sin, sizeof (sin)) < 0)
{
perror("simplex-talk: connect");
close(s);
exit(1);
}
printf("Connection Succeeded\n");
/* main loop: get and send lines of text */
float total = 0;
while (read(fd, buf, MAX_LINE))
{
//usleep(1000);;
len = strlen(buf) + 1;
total += send(s, buf, len, 0);
//printf("%fKB and %fMB\n",total/1024, total/(1024*1024));
}
send(s, "close", 6, 0);
close(fd);
}
Just if i replace use of file descriptors with pointers and use fgets and fputs to read and write then my file transfer does not take properly. But if i use file descriptors then i am not able to read the text file that i sent. Text editors shows some binary data in the file.
while (read(fd, buf, MAX_LINE))
{
//usleep(1000);;
len = strlen(buf) + 1;
total += send(s, buf, len, 0);
//printf("%fKB and %fMB\n",total/1024, total/(1024*1024));
}
There is an issue here, you have no guarantee that read will read a zero byte so strlen(buf) is potentially dangerous. Also note, that as you set len to strlen(buf) + 1, if you do encouter a zero byte you will send it across the socket but if you don't read a zero byte, strlen will read beyond the end of the array and send 'junk' across the socket.
It would be sensible to store the return value of read so that you know how many bytes were actually read from fd.
while (len = recv(new_s, buf, MAX_LINE, 0) && strcmp(buf,"close"))
{
buf[len] = 0;
total = total+len;
//write(stdout, buf, len);
write(fd, buf, len);
//printf("%fKB and %fMB\n",total/1024, total/(1024*1024));
}
Your receive side seems to assume that each call to recv won't include a zero byte as you manually terminate the buffer with a 0. Note that you don't actually have room to do this if recv actually receives MAX_LINE bytes as buf only consists of MAX_LINE elements. As your write is restricted by length in any case, there is no need to do buf[len] = 0;.
Related
I am learning linux socket programming, I expect that server can read data, even I add a delay but it just drops the buffer data, and receive the recent data, that is why, Thanks. The code has been presented.
By the way, Could you show a common practice to deal with this kind of situation?
Server side C/C++ program to demonstrate Socket programming
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080
int main(int argc, char const *argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
const char hello[] = "Hello from server";
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address)) < 0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t *)&addrlen)) < 0)
{
perror("accept");
exit(EXIT_FAILURE);
}
for (int i = 0;; i++)
{
sleep(5);
valread = read(new_socket, buffer, 1024);
printf("%s\n", buffer);
}
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
return 0;
}
Client side C/C++ program to demonstrate Socket programming
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>
#include <string.h>
#define PORT 8080
int main(int argc, char const *argv[])
{
int sock = 0, valread;
struct sockaddr_in serv_addr;
const char data[] = "Hello from client";
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
for (int i = 0;; i++)
{
sleep(1);
std::string hello = std::string(data) + std::to_string(i);
if (send(sock, hello.c_str(), hello.length() + 1, 0) != hello.length() + 1)
{
printf("error send %d \n", i);
}
printf("Hello message sent %d\n", i);
}
valread = read(sock, buffer, 1024);
printf("%s\n", buffer);
return 0;
}
The problem is, that the messages get concatenated in the socket. The socket represents a byte stream. Your sender puts bytes into the stream every second. On the first iteration, it writes "Hello from client0\0" (19 bytes) to the stream.
After one second, it writes "Hello from client1\0", and then "Hello from client2\0", "Hello from client3\0" and "Hello from client4\0", Now, after 5 Seconds, 5*19 = 95 bytes are written to the byte stream.
Now, the receiver calls valread = read(new_socket, buffer, 1024);. Guess what, it reads all 95 bytes (because you specified 1024 as buffer size) and sets valread to 95.
Then you call printf("%s\n", buffer);, which only prints the first 18 bytes of buffer, because there is a '\0' as 19th byte, which terminates '%s' format. Allthough 95 bytes are received, 76 bytes are missing in the output of your program.
If you use '\n' instead of '\0' as message separator and use write(1, buffer, valread) instead of printf("%s\n") on the receiving side, you will see all your data.
std::string hello = std::string(data) + std::to_string(i) + "\n";
if (send(sock, hello.c_str(), hello.length(), 0) != hello.length()) ...
Conclusion:
Stream sockets realize byte sreams, the do not preserve message boundaries.
If message bounaries must be preserved, you need to use a protocol on top of the stream to mark your message boundaries. The proptocol could be as simple as using '\n' as a message seaparator, as long as '\n' is not part of your message payload (e.g. when unsign a simple text protocol).
You block the server for 5 seconds and it cannot receive some messages from the client.
for (int i = 0;; i++)
{
sleep(5);
valread = read(new_socket, buffer, 1024);
printf("%s\n", buffer);
}
How can a client check if the server is receiving a message? I think this was discussed in Linux socket: How to make send() wait for recv()
P.S. It looks like there is a synchronizing piece of code, but you pulled it out of the loop.
Server:
}
send(new_socket, hello, strlen(hello), 0);
Client:
}
valread = read(sock, buffer, 1024);
I'm a newbie in socket programming. I'm trying to make a server/ client program to download a file.
Firstly, i init some step that i usually do in other program for set up a connection form client to server.
Next, From server side, I'm try to in put number of bytes that send to client to set up the receive buffer's size. From client side, I receive the number in string type. I convert it to long type and set it to buffer size.
Then, From client side, I enter the name of file that need to download from server. Server receive the name and check if it exist or not.
Last step ( THE PROBLEM STEP, i think ) server try to open file. if file is opened, send the file name back to client. client check file name if it same what it sent or not.
======> my problem is file name sent back to client:
- From server side: I print it out and check. it's correct.
- From client: I print buffer out right after read from server. It's not correct. sometimes, it's empty. sometimes, it's some-random-value.
I have done exactly like previous step.
Server.cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2)
{
perror("you have to input port");
exit(1);
}
// init sockfd
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("sockfd perror");
exit(1);
}
// sockopt
int opt = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
// init server
bzero(&serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
// bind port
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
perror("ERROR on binding");
exit(1);
}
listen(sockfd, 5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
{
perror("ERROR on accept");
exit(1);
}
char buffer[256];
// write buff size
int buffsize;
printf("Input recive buffsize in Byte: ");
scanf("%d", &buffsize);
if (buffsize <= 0)
{
perror("Buffer size must be > 0");
exit(1);
}
bzero(buffer, sizeof(buffer));
bcopy(to_string(buffsize).c_str(), buffer, sizeof(buffer));
n = write(newsockfd, buffer, sizeof(buffer));
if (n < 0)
{
perror("fail to send buffer size");
exit(0);
}
//read file name
bzero(buffer, sizeof(buffer));
n = read(newsockfd, buffer, sizeof(buffer));
if (n < 0)
{
perror("ERROR reading from socket");
exit(1);
}
// open file:
char filename[strlen(buffer) + 1];
bcopy(buffer, filename, sizeof(filename));
FILE *pf;
unsigned long fsize;
pf = fopen(filename, "rb");
if (pf == NULL)
{
bzero(buffer, sizeof(buffer));
bcopy("File not found", buffer, sizeof(buffer));
n = write(newsockfd, buffer, sizeof(buffer));
if (n < 0)
{
perror("ERROR writing to socket");
exit(1);
}
printf("File not found!\n");
return 1;
}
else
{
printf("File %s is openned \n", filename);
fseek(pf, 0, SEEK_END);
fsize = ftell(pf);
rewind(pf);
printf("File has %ld bytes!\n", fsize);
}
// write OK response file name
bzero(buffer, sizeof(buffer));
bcopy(filename, buffer, sizeof(buffer));
printf("\n\n\n\n%s\n\n\n\n", buffer);
n = write(newsockfd, buffer, sizeof(buffer));
if (n < 0)
{
perror("ERROR writing to socket");
exit(1);
}
close(newsockfd);
close(sockfd);
return 0;
}
Client.cpp
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
if (argc < 3)
{
fprintf(stderr, "usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
// init sockfd
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("sockfd error");
exit(1);
}
// init server
server = gethostbyname(argv[1]);
if (server == NULL)
{
fprintf(stderr, "ERROR, no such host\n");
exit(0);
}
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
serv_addr.sin_port = htons(portno);
// connect
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
perror("ERROR connecting");
exit(1);
}
// recive and set buffer size:
char tempBuff[10];
bzero(tempBuff, 10);
n = read(sockfd, tempBuff, sizeof(tempBuff));
if (n < 0)
{
perror("fail to recive buffer size");
exit(1);
}
char buffer[stol(string(tempBuff))];
printf("Connect succes, Buffer size is %ld Bytes\n", sizeof(buffer));
// input file:
printf("Input file name to download: ");
string filename;
cin >> filename;
// Send filename
bzero(buffer, sizeof(buffer));
bcopy(filename.c_str(), buffer, filename.length());
n = write(sockfd, buffer, strlen(buffer));
if (n < 0)
{
perror("ERROR writing to socket");
}
// read file name response
bzero(buffer, sizeof(buffer));
n = read(sockfd, buffer, sizeof(buffer));
if (n < 0)
{
perror("ERROR reading from socket");
}
printf("\n\n\n\n%s, %ld\n\n\n\n", buffer, strlen(buffer));
// if (strcmp(buffer, filename.c_str()) == 0)
// {
// printf("OK!\n");
// }
// else
// {
// perror("Wrong filename");
// printf("server msg: %s\n", buffer);
// exit(1);
// }
close(sockfd);
return 0;
}
RUN CODE WITH FOLLOWING COMMAND:
Client: ./client [server ip] [port]
Server: ./server [port]
My result:
Update 1: problem disappear when i remove these line:
// write buff size
int buffsize;
printf("Input recive buffsize in Byte: ");
scanf("%d", &buffsize);
if (buffsize <= 0)
{
perror("Buffer size must be > 0");
exit(1);
}
at server.cpp
and these line:
// recive and set buffer size:
bzero(tempBuff, sizeof(tempBuff));
n = read(sockfd, tempBuff, sizeof(tempBuff));
if (n < 0)
{
perror("fail to recive buffer size");
exit(1);
}
// char buffer[stol(string(tempBuff))];
at client.cpp
I solved it. this problem occur due to tempBuff is too small. it's just 10 bytes. Using bigger tempBuff will solve the problem.
I am using this code to receive data from a sensor through sockets. The problem is that I keep receiving the same output for every iteration of the for loop. However I receive a different number for every time I run the code but again, the same number keeps repeating. The sensor should send different every time data but thats not the case here.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "port.h"
#define BUFSIZE 2048
int
main(int argc, char **argv)
{
struct sockaddr_in myaddr; /* our address */
struct sockaddr_in remaddr; /* remote address */
socklen_t addrlen = sizeof(remaddr); /* length of addresses */
int recvlen; /* # bytes received */
int fd; /* our socket */
int msgcnt = 0; /* count # of messages we received */
unsigned char buf[BUFSIZE]; /* receive buffer */
/* create a UDP socket */
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("cannot create socket\n");
return 0;
}
/* bind the socket to any valid IP address and a specific port */
memset((char *)&myaddr, 0, sizeof(myaddr));
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
myaddr.sin_port = htons(SERVICE_PORT);
if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
perror("bind failed");
return 0;
}
/* now loop, receiving data and printing what we received */
printf("waiting on port %d\n", SERVICE_PORT);
printf("%s \n \n", "We recieve 10 packets just to confirm the communication");
recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
if (recvlen > 0) {
buf[recvlen] = 0;
printf("received message: \"%u\" (%d bytes)\n", buf, recvlen);
}
else
printf("uh oh - something went wrong!\n");
sprintf(buf, "ack %d", msgcnt++);
printf("sending response \"%u\"\n", buf);
if (sendto(fd, buf, strlen(buf), 0, (struct sockaddr *)&remaddr, addrlen) < 0)
perror("sendto");
int temp = recvlen;
for (;;) {
recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
if (recvlen > 0) {
buf[recvlen] = 0;
printf("received message: \"%u\" (%d bytes)\n", buf, recvlen);
}
}
}
Edit:
Here is the output when i ran the code two seperate times:
trial run and
trial run 2
I believe the problem isn't with your networking code but rather with your printf() calls:
printf("received message: \"%u\" (%d bytes)\n", buf, recvlen);
You are specifying %u to print out the contents of buf, but buf is a char array (not an unsigned integer), so you probably want to be using %s instead.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
a Simple Server and Client that I can send the file,
And I need you guys to see if this source are done.
Cuz I think it won't download the full file.
And maybe to this source have a limit ? Cuz I uploaded/downloaded 200K and a little bit more ..
Server:
#include <WinSock2.h>
#include <Windows.h>
#include <stdio.h>
#pragma comment(lib, "Ws2_32.lib")
SOCKET Socket, Sub;
WSADATA Winsock;
sockaddr_in Addr;
int Addrlen = sizeof(sockaddr_in);
char Buffer[256];
char *Str;
sockaddr_in IncomingAddress;
int AddressLen = sizeof(IncomingAddress);
int main()
{
WSAStartup(MAKEWORD(2, 2), &Winsock); // Start Winsock
if(LOBYTE(Winsock.wVersion) != 2 || HIBYTE(Winsock.wVersion) != 2) // Check version
{
WSACleanup();
return 0;
}
Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
ZeroMemory(&Addr, sizeof(Addr));
Addr.sin_family = AF_INET;
Addr.sin_port = htons(6091);
bind(Socket, (sockaddr*)&Addr, sizeof(Addr));
if(listen(Socket, 1) == SOCKET_ERROR)
{
printf("listening error\n");
}
else
{
printf("listening ok\n");
}
if(Sub = accept(Socket, (sockaddr*)&IncomingAddress, &AddressLen))
{
char *ClientIP = inet_ntoa(IncomingAddress.sin_addr);
int ClientPort = ntohs(IncomingAddress.sin_port);
printf("Client conncted!\n");
printf("IP: %s:%d\n", ClientIP, ClientPort);
printf("Sending file .. \n");
FILE *File;
char *Buffer;
unsigned long Size;
File = fopen("C:\\Prog.exe", "rb");
if(!File)
{
printf("Error while readaing the file\n");
goto End;
}
fseek(File, 0, SEEK_END);
Size = ftell(File);
fseek(File, 0, SEEK_SET);
Buffer = new char[Size];
fread(Buffer, Size, 1, File);
char cSize[MAX_PATH];
sprintf(cSize, "%i", Size);
fclose(File);
send(Sub, cSize, MAX_PATH, 0); // File size
send(Sub, Buffer, Size, 0); // File Binary
free(Buffer);
End:
closesocket(Sub);
closesocket(Socket);
WSACleanup();
}
getchar();
return 0;
}
Client:
#include <WinSock2.h>
#include <Windows.h>
#include <stdio.h>
#pragma comment(lib, "Ws2_32.lib")
SOCKET Socket;
WSADATA Winsock;
sockaddr_in Addr;
int Addrlen = sizeof(Addr);
int main()
{
WSAStartup(MAKEWORD(2, 2), &Winsock); // Start Winsock
if(LOBYTE(Winsock.wVersion) != 2 || HIBYTE(Winsock.wVersion) != 2) // Check version
{
WSACleanup();
return 0;
}
Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
ZeroMemory(&Addr, sizeof(Addr)); // clear the struct
Addr.sin_family = AF_INET; // set the address family
Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
Addr.sin_port = htons(6091); // set the port
if(connect(Socket, (sockaddr*)&Addr, sizeof(Addr)) < 0)
{
printf("Connection failed !\n");
getchar();
return 0;
}
printf("Connection successful !\n");
printf("Receiving file .. \n");
int Size;
char *Filesize = new char[1024];
if(recv(Socket, Filesize, 1024, 0)) // File size
{
Size = atoi((const char*)Filesize);
printf("File size: %d\n", Size);
}
char *Buffer = new char[Size];
if(recv(Socket, Buffer, Size, 0)) // File Binary
{
FILE *File;
File = fopen("Prog.exe", "wb");
fwrite((const char*)Buffer, 1, Size, File);
fclose(File);
}
getchar();
closesocket(Socket);
WSACleanup();
return 0;
}
Thanks.
Your code may fail if you try to send/receive large amount of data. From the documentation of the send function:
Return value
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, and
a specific error code can be retrieved by calling WSAGetLastError.
You have to check the return value of send(), and if it is less than the number of bytes requested to be sent, call send() again for the remaining data. Example:
char *data = Buffer; // data to be sent
int len = Size; // number of bytes to be sent
while (len > 0) {
int amount = send(Sub, data, len, 0);
if (amount == SOCKET_ERRROR) {
// handle error ...
} else {
len -= amount;
data += amount;
}
}
The same is true for the recv() call in the client.
This is the file send function which will read the file as binary and will send the data. This is an independent function just pass the value of the socket on which v need to send the data along with the file path which we need to send.
void FileSend(SOCKET FileSendSocket,char *FilePath)
{
streampos filesize = 0;
ifstream in(FilePath,ios::binary);
ZeroMemory( &sendbuf, sendbuflen);
if(in.is_open())
{
while(1)
{
in.read(sendbuf,sendbuflen);
if(in.eof())
{
cout << "End of File sending from Client" << endl;
in.close();
break;
}
else
{
send(FileSendSocket,sendbuf,sendbuflen,0);
ZeroMemory( &sendbuf, sendbuflen);
}
}
}
}
And this is the receive function on the client side and it should be called just next to the receive function this function will continuously write what ever data the server is sending.
ofstream out("C:\\Prog.exe",ios::binary);
void FileReceive(char* recvbuf, int recvbuflen)
{
if(out.is_open())
{
out.write(recvbuf,recvbuflen);
ZeroMemory(&recvbuf,recvbuflen);
}
}
I made a server and client that should transfer files.
I tried to make it read the whole file and send it.
But now as I see it, I am having a problem.
Server should automatically send the file when the client is connected.
But the file is empty, and I don't know where the problem is
You can see that I'm trying to send .txt file. But I would like in the future send a big file, but not bigger than 1MB.)
Edit:
Picture here: http://img819.imageshack.us/img819/8259/aadi.jpg
Left side: The file that I tried to send.
Right side: The file I received
The Problem: The file that I received has been damaged, and I can't use it.
Server:
#include <WinSock2.h>
#include <Windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "Ws2_32.lib")
#define Port 6000
SOCKET Socket, Sub;
WSADATA Winsock;
sockaddr_in Addr;
sockaddr_in IncomingAddress;
int AddressLen = sizeof(IncomingAddress);
int main()
{
WSAStartup(MAKEWORD(2, 2), &Winsock); // Start Winsock
if(LOBYTE(Winsock.wVersion) != 2 || HIBYTE(Winsock.wVersion) != 2) // Check version
{
WSACleanup();
return 0;
}
Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
ZeroMemory(&Addr, sizeof(Addr));
Addr.sin_family = AF_INET;
Addr.sin_port = htons(Port);
bind(Socket, (sockaddr*)&Addr, sizeof(Addr));
if(listen(Socket, 1) == SOCKET_ERROR)
{
printf("listening error\n");
}
else
{
printf("listening ok\n");
}
if(Sub = accept(Socket, (sockaddr*)&IncomingAddress, &AddressLen))
{
char *ClientIP = inet_ntoa(IncomingAddress.sin_addr);
int ClientPort = ntohs(IncomingAddress.sin_port);
printf("Client conncted!\n");
printf("IP: %s:%d\n", ClientIP, ClientPort);
printf("Sending file .. \n");
FILE *File;
char *Buffer;
unsigned long Size;
File = fopen("C:\\Prog.rar", "rb");
if(!File)
{
printf("Error while readaing the file\n");
getchar();
return 0;
}
fseek(File, 0, SEEK_END);
Size = ftell(File);
fseek(File, 0, SEEK_SET);
Buffer = new char[Size];
fread(Buffer, Size, 1, File);
char cSize[MAX_PATH];
sprintf(cSize, "%i", Size);
fclose(File);
send(Sub, cSize, MAX_PATH, 0); // File size
//int len = Size;
//char *data = Buffer;
int Offset = 0;
while(Size > Offset)
{
int Amount = send(Sub, Buffer + Offset, Size - Offset, 0);
if(Amount <= 0)
{
cout << "Error: " << WSAGetLastError() << endl;
break;
}
else
{
Offset += Amount;
printf("2\n");
}
}
free(Buffer);
closesocket(Sub);
closesocket(Socket);
WSACleanup();
}
getchar();
return 0;
}
Client:
#include <WinSock2.h>
#include <Windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "Ws2_32.lib")
SOCKET Socket;
WSADATA Winsock;
sockaddr_in Addr;
int Addrlen = sizeof(Addr);
int main()
{
WSAStartup(MAKEWORD(2, 2), &Winsock); // Start Winsock
if(LOBYTE(Winsock.wVersion) != 2 || HIBYTE(Winsock.wVersion) != 2) // Check version
{
WSACleanup();
return 0;
}
Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
ZeroMemory(&Addr, sizeof(Addr)); // clear the struct
Addr.sin_family = AF_INET; // set the address family
Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
Addr.sin_port = htons(6000); // set the port
if(connect(Socket, (sockaddr*)&Addr, sizeof(Addr)) < 0)
{
printf("Connection failed !\n");
getchar();
return 0;
}
printf("Connection successful !\n");
printf("Receiving file .. \n");
int Size;
char *Filesize = new char[1024];
if(recv(Socket, Filesize, 1024, 0)) // File size
{
Size = atoi((const char*)Filesize);
printf("File size: %d\n", Size);
}
char *Buffer = new char[Size];
//int len = Size;
//char *data = Buffer;
int Offset = 0;
while(Size > Offset)
{
int Amount = recv(Socket, Buffer + Offset, Size - Offset, 0);
if(Amount <= 0)
{
cout << "Error: " << WSAGetLastError() << endl;
break;
}
else
{
Offset += Amount;
printf("2\n");
}
}
FILE *File;
File = fopen("Prog.rar", "wb");
fwrite(Buffer, 1, Size, File);
fclose(File);
getchar();
closesocket(Socket);
WSACleanup();
return 0;
}
The send API may not send all the data you requested to send. So, you have to pay attention to the return value, and retry the send from where the last send ended. As an example:
offset = 0;
while (offset < bufsize) {
r = send(socket, buf+offset, bufsize-offset);
if (r <= 0) break;
offset += r;
}
While you are doing something similar for your file transfer, you do not make sure this is the case for your file size.
When you send the file size, you only need to send the string that represents the size, not the entire MAX_PATH. The receiver then needs to parse the first string to determine the size, but any data read in after the end of the first string needs to be considered part of the file. However, since you are trying the send MAX_PATH, the receiver should receive the same amount. Your client code receives 1024 bytes, but there is no indication this is the same size as MAX_PATH.
The recv API may also return fewer bytes than requested. You use a loop to handle reading the file, but you may need a loop to read the entire message that contains the file size.
In your client receive loop, you are incrementing the data pointer. This makes it unusable to write out the file later. You already have Buffer though, so use that to write out your file.
fwrite(Buffer, 1, len, File);
If you encounter an error doing socket I/O, you can retrieve the error with WSAGetLastError(), or you can issue getsockopt() on the socket with the SO_ERROR option. These may return different values, but the error reason should be correlated.
Myself faced the same problem and after googling found that send() api can send a maximum data based on low level TCP buffers which are os dependent.So inorder to send a huge file we need to perform file chunking , ie send the file in the form of chunks.
`const int FILE_CHUNK_SIZE = 2000;
//get file size
ifstream file("myFile.file", ios::binary);
file.seekg(0, ios::end);
unsigned int fileSize = file.tellg();
file.close();
//get the file
char* fileBuffer = new char[fileSize];
file.open("myFile.file", ios::binary);
file.seekg (0, ios::beg);
file.read (fileBuffer, fileSize);
file.close();
//send file in chunks
unsigned int bytesSent = 0;
int bytesToSend = 0;
while(bytesSent < fileSize)
{
if(fileSize - bytesSent >= FILE_CHUNK_SIZE)
bytesToSend = FILE_CHUNK_SIZE;
else
bytesToSend = fileSize - bytesSent;
send(ConnectSocket, fileBuffer + bytesSent, bytesToSend, 0 );
bytesSent += bytesToSend;
}
delete [] fileBuffer;`
At the receiving end we need to have a recv() api called till the whole file content is read.
credits to:shacktar cplusplus.com