This is for educational purpose (University assignment).
I need to write a client-server programs in C for Linux. (I already have that part. A client connects to the server, it sends and receive files without a problem…).
When a client connects to the server, it sends the server a list of files on the client. So the server has a list of all the files on it’s clients.
A client A can request from the server a file “test.txt”, the server knows that the file is on client B, and the file should be transferred from B to A. I’m trying to think about the best way of doing this.
- recv from B into a buffer, and immediatly send() the buffer to A?
- recv() the whole file from B and save it on server ,then send it
to A?
My programs should support this behavior:
if A asks a file from B, and then C asks a file from B, C should NOT wait until the transfer A<–>B will end. And this is where I get stuck.
Thank you very much!!
Edit: My server is using threads: whenever a new client is connecting, a new thread is opened to serve it. My client, at this moment, does not use threads (this can be changed).
If you want to do several transfers at once using sockets you have two options:
Blocking sockets and threads
This is the way you’ve written your server. The problem with threads is that they can lead to bugs that are rather hard to debug. Combine that with network bugs that in themselves can be rather hard to debug and you have a potential nightmarish debugging session on your hands.
Non-blocking sockets and select()
This way doesn’t need threads, instead it uses select() to see which sockets have data waiting to be read. Combine that with some loops and you can transfer several files concurrently. Setting sockets to be non-blocking is easy, using correct can be slightly trickier but weighted against the potential for thread + network bugs this is the way I personally prefer to write network code.
Regarding your actual problem; I would suggest something like this: