Hello every one I want to ask a question about file transfer using sockets. I have made a code of client server after connection I open the file at client side and start reading the data and send that data to server. Server opens a file read that data from socket and write it to file. It's working fine but now I want that my file name should be same at both sides. To achieve this I have send the file name from client side to server but the problem is that the server reads the file name and also read some data and make the wrong file name.
for example
file name: myfile.txt
data in the file is : hello how are you.
server create the file name myfile.txthellow how
How can I avoid this as I dont know that what is the size of file name at server size Thanks
You have to send the length of the filename to the server. There are two ways to do this:
Also, beware that a single
recv
call may read data sent from multiplesend
s on the other side: This is how TCP works (TCP is a stream-oriented protocol): do not assume data sent in onesend
command will arrive in onerecv
. Onerecv
may get data from one or moresend
commands, and data from one or moresend
commands might be received in a singlerecv
command. (And you might get "half asend
" too).There are several options:
NUL
or\n
).On the receiving end, both the file name and the data will arrive as a single stream of bytes. However, the server now has enough information to figure out where the file name ends and the data begins.
You can define a custom protocol with two types of messages: one type for the filename and another for data. each message is composed of a first byte indicating its type (the header) and the remaining bytes containing either filename or data (the body).