views:

349

answers:

3

The situation is that I'm trying to write a server script that accepts file transfers from a client. I figured out how to make and connect to and from the server using the TCP protocol. However I was wondering how do you transfer a binary file in ruby?

I mean you can open a binary file, but what steps are necessary to be able to transfer it? Is TCP stream idea? What about UDP?

+1  A: 

As far as sockets go, there's nothing to really distinguish between "binary" data and non-binary data, as it's all the same. They are just streams of data and it is the responsibility of the applications on either end to correctly format and interpret the communications.

Without some kind of framing on your data it will be hard to determine if the transmitted data is complete and valid. An example of how this is done is the HTTP specification, although many others exist, some of which are quite simple such as FTP.

Ideally you can make use of an existing specification without having to resort to rolling your own, and there are specifications such as BEEP which can serve as useful, robust, generic examples.

tadman
+1  A: 

I think I found a solution.

Using SFTP, I can upload files over an SSH connection to the server:

require 'net/sftp'

Net::SFTP.start('host', 'username', :password => 'password') do |sftp|
  # upload a file or directory to the remote host
  sftp.upload!("/path/to/local", "/path/to/remote")

  # download a file or directory from the remote host
  sftp.download!("/path/to/remote", "/path/to/local")
end

However this isn't really what I was looking for as the above relies on using SSH. I was hoping it to be independent.

chutsu
+1 for using a secure protocol that you do not need to re-debug yourself. Unless of course you are just trying to learn how to work with the low-level sockets and this is a practice exercise.
Andrew Y
+1  A: 

Well, if you wrote your own client and your own server it prety much sums up to

socket.write(data)

since a socket is just an IO object. And then terminating your input (of course you will need to invent your own escaping, or send length beforehand - invent a protocol from scratch).

Julik
I'm sure some one has done this before. Isn't there a simple protocol I can follow?
chutsu
'course you can! Just use plain HTTP or FTP.
Julik