代码改变世界

transfering a file over TCP

2006-09-22 12:06  Jeff  阅读(529)  评论(0编辑  收藏  举报

Question:
  I am a nertwork programming newbie. I am trying to write a
client-server pair such that the client should be able to transfer a
file over TCP connection to the server.
  The only way I know of, is to open the file, read into buffer and write
into the socket. Is there any function call to just transfer the file?

Answer:
   This is basically what you must do.
   But you should probably add a EOF protocol (eg: write the file size
before sending the data).  You may also want to transfer several files
(eg sending the file directory/name and perhaps other attributes such
as owner, access rights, etc).
   Now, TCP corrects some errors, but it normally computes a 2-byte check
sum on each packet, so the probability to have a undetected bad packet
is still rather high.  And the more so when you transfer long files.
   So, I would add a more sophisticated error detection algorithm
(eg. doing md5sums on each 100 KB or 1 MB blocks).
   Often, you want to get the directory listing of the remote side before
sending or receiving a file.  So you need to add some protocol to send
such commands and transfer directory "files".
   Sometimes you don't want the file data to be sent in clear over TCP
either. Anybody on the network could see it...  So you may want to
encrypt the data, using ssl perhaps?
   Are you aware that there is already this FTP protocol (and some other
ISO file transfer protocols), and implementations, in addition to scp
and sftp?
   In Linux, there's sendfile(2). There's no recvfile though.
   Other Unixes often implement sendfile  with  different  semantics
   and prototypes. It should not be used in portable programs.