问题
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:
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.
回答2:
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.
回答3:
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).
来源:https://stackoverflow.com/questions/1267736/how-to-transfer-a-binary-file-or-any-file-to-a-remote-server-ruby