Sending a file from server side to client side using TCP in C++
Now this is a bit more of a request since I am not able to find any simple and direct example for this.
Issue: I want to send a file from the server side to the client side.
When the server is already up and listening on a port and the client requests a fi开发者_如何学Cle (file's name being accepted as a parameter with the server IP address such as 127.0.0.1 and port no.) and then the process of transfer starts till the file is copied.
Also can someone incorporate how can i measure the average transfer speed on the server side?
BTW: I am running Linux x86 Cheers, echo9
Check Beej's Guide to Network Programming. There are lots of examples there that shows how to implement a client/server architecture using sockets and send data between them.
EDIT:
Check items 8 and 9 from this tutorial for a complete example on client/server. Note that on item 8, the server sends a char*
to the client:
send(fd2,"Welcome to my server.\n",22,0); /* send to the client welcome message */
On this case, it's the "Welcome to my server.\n"
string, and the next parameter is the size of the string you want to send.
When you need to send data from a file it's the same thing: first, you need to read the data from the file and store it in a char* buffer;
that you manually allocated through malloc().
Something like this:
char* buffer;
buffer = (char*) malloc(1024); // let's say your file has 1KB of data
/* insert here the code to read data from the file and populate buffer with it */
send(fd2, buffer, 1024,0);
Here's a simple protocol:
CLIENT SERVER
socket(), bind(), listen()
socket(), connect()
accept()
send("GET filename\n")
recv(buffer)
inspect buffer, parse filename (stop at space or \n),
open() file.
sendfile(file, socket)
close(socket)
close(file)
recv(socket)
close()
This protocol has the advantage of being able to use your web browser as the client, and your web server as the host, assuming they each support HTTP/0.9.
Here's a client.
You might want to consider using sendfile(2).
精彩评论