GO语言学习:使用io.copyN实现网络文件传输

一.  首先先看一下io.copy的定义:

func CopyN

func CopyN(dst Writer, src Reader, n int64) (written int64, err error)

CopyN copies n bytes (or until an error) from src to dst. It returns the number of bytes copied and the earliest error encountered while copying. On return, written == n if and only if err == nil.

If dst implements the ReaderFrom interface, the copy is implemented using it.

其中有主要两个参数 dst和src:

dst是Writer接口的实例    ->  只要能实现Writer接口功能,就可以做dst

src是Reader接口的实例  ->  只要能实现Reader接口功能,就可以做src

n就是要传送的内容大小


二. 网络传输需要的net.Conn的定义:

type Conn interface {
        // Read reads data from the connection.
        // Read can be made to time out and return a Error with Timeout() == true
        // after a fixed time limit; see SetDeadline and SetReadDeadline.
        Read(b []byte) (n int, err error)

        // Write writes data to the connection.
        // Write can be made to time out and return a Error with Timeout() == true
        // after a fixed time limit; see SetDeadline and SetWriteDeadline.
        Write(b []byte) (n int, err error)

可见net.Conn中可以实现Writer及Reader接口的功能。


三. os.File的定义

func (*File) Read

func (f *File) Read(b []byte) (n int, err error)

Read reads up to len(b) bytes from the File. It returns the number of bytes read and an error, if any. EOF is signaled by a zero count with err set to io.EOF.

func (*File) Write

func (f *File) Write(b []byte) (n int, err error)

Write writes len(b) bytes to the File. It returns the number of bytes written and an error, if any. Write returns a non-nil error when n != len(b).

显而易见,File亦可以做Writer和Reader的实例


四.os.FileInfo的定义

type FileInfo

type FileInfo interface {
        Name() string       // base name of the file
        Size() int64        // length in bytes for regular files; system-dependent for others
        Mode() FileMode     // file mode bits
        ModTime() time.Time // modification time
        IsDir() bool        // abbreviation for Mode().IsDir()
        Sys() interface{}   // underlying data source (can return nil)
}

A FileInfo describes a file and is returned by Stat and Lstat.

func Lstat

func Lstat(name string) (FileInfo, error)

Lstat returns a FileInfo describing the named file. If the file is a symbolic link, the returned FileInfo describes the symbolic link. Lstat makes no attempt to follow the link. If there is an error, it will be of type *PathError.

使用Lstat可以获取File的信息,其中我们需要的是Size()

五. 实现方法

1. 建立服务器端传输桥梁

服务器主要起桥梁的作用,即io.CopyN(net.Conn, net.Conn,os.FileInfo.Size),其中第一个就是服务器与目标客户端的链接,第二个就是服务器与源客户端的链接,做好传递数据的准备,第三个就是要传送的文件大小

2. 建立目标客户端的接受准备

首先使用os.Create建立最终要获取数据的文件,然后实现io.CopyN(os.File, net.Conn,os.FileInfo.Size()),其中os.File就是之前建立的文件,net.Conn就是与服务器的链接

3.开始传输数据

首先使用os.Open打开需要传输的文件,然后使用os.Lstat获取FileInfo,然后开始传输io.CopyN(net.Conn, os.File,os.FileInfo.Size()), 其中net.File就是与服务器的链接,os.File就是之前打开的文件。


经过这三步即可完成网络文件传输。




你可能感兴趣的:(go)