File Transfer application

2019-08-10 15:45发布

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

标签: c linux sockets
3条回答
姐就是有狂的资本
2楼-- · 2019-08-10 15:59

You have to send the length of the filename to the server. There are two ways to do this:

  • Explicitly send the length of the filename, then the filename to the server.
  • Implicitly send the length by terminating the filename with a special character, typically a nul ('\0' or 0 byte)

Also, beware that a single recv call may read data sent from multiple sends on the other side: This is how TCP works (TCP is a stream-oriented protocol): do not assume data sent in one send command will arrive in one recv. One recv may get data from one or more send commands, and data from one or more send commands might be received in a single recv command. (And you might get "half a send" too).

查看更多
唯我独甜
3楼-- · 2019-08-10 16:06

There are several options:

  1. Send a special character after the file name (e.g. NUL or \n).
  2. Prefix the file name with its length in bytes.

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.

查看更多
仙女界的扛把子
4楼-- · 2019-08-10 16:25

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).

查看更多
登录 后发表回答