Go network file transfer

Time:2020-2-22

Process analysis

With the help of TCP, the basic idea is as follows:

  1. The sender (client) sends the file name to the server, and the server saves the file name.
  2. The receiver (server) returns a message OK to the client to confirm that the file name is saved successfully.
  3. After receiving the message, the sender (client) begins to send the file data to the server.
  4. The receiver (server) reads the content of the file and writes it to the previously saved file.

Because the file transmission needs a stable and reliable connection, TCP mode is used to complete the network file transmission function.

Go network file transfer

First get the filename. The stat() function in the OS package is used to obtain the file attribute information. Include the file name and file size in the file properties returned by the function. Stat parameter name passed in the absolute path of file access. The name() function in FileInfo can extract the file list independently.

func Stat(name string) (fi FileInfo, err error)

Stat returns a FileInfo that describes the file object specified by name. If the specified file object is a symbolic link, the returned FileInfo describes the information of the file that the symbolic link points to, and this function will try to jump the link. If there is an error, the error value returned is of type * patherror.

We can know from the source code that FileInfo is an interface. To implement this interface, we must implement all the following methods of this interface

Go network file transfer

In fact, the realization of network file transmission relies on the knowledge of local file copying and TCP network programming. You can first look at the copying files of go language and go network programming to understand the relevant content.

So the general steps of using TCP to realize file transfer can be summed up as follows

Go network file transfer

Receiver:

  1. Create a listener and close it at the end of the program.
  2. Block and wait for the client to connect to Conn, and close conn at the end of the program.
  3. Read client send file name. Save the filename.
  4. Send back “OK”.
  5. The encapsulation function recvfile receives the file content sent by the client. Parameters filename and conn
  6. Create file by filename, close at the end
  7. Loop read the network file content of the sender. When reading 0, it means that the file has been read.
  8. Write the read content to the created file intact

Receiver code:

package main

import (
    "fmt"
    "io"
    "net"
    "os"
)

func recvFile(conn net.Conn, fileName string) {
    //Create a new file by file name
    file, err := os.Create(fileName)
    if err != nil {
        FMT. Printf ("OS. Create() function execution error, error is:% v \ n", ERR)
        return
    }
    defer file.Close()

    //Read data from network and write to local file
    for {
        buf := make([]byte, 4096)
        n, err := conn.Read(buf)

        //Write to local file, read and write
        file.Write(buf[:n])
        if err != nil {
            if err == io.EOF {
                FMT. Printf ("receive file complete. \n ""
            } else {
                FMT. Printf ("conn.read() method execution error, error is:% v \ n", ERR)
            }
            return
        }
    }
}

func main() {

    //1. Create a listening socket
    listener, err := net.Listen("tcp", "127.0.0.1:8000")
    if err != nil {
        FMT. Printf ("net. Listen() function execution error, error is:% v \ n", ERR)
        return
    }
    defer listener.Close()

    //Blocking monitor
    conn, err := listener.Accept()
    if err != nil {
        FMT. Printf ("listener. Accept() method execution error, error is:% v \ n", ERR)
        return
    }
    defer conn.Close()

    //The file name cannot be longer than 1024 bytes
    buf := make([]byte, 4096)
    n, err := conn.Read(buf)
    if err != nil {
        FMT. Printf ("conn.read() method execution error, error is:% v \ n", ERR)
        return
    }
    fileName := string(buf[:n])

    //Write back OK to the sender
    conn.Write([]byte("ok"))

    //Get file content
    recvFile(conn, fileName)
}

Sending end:

  1. Prompts you to enter a file name using command line parameters. Receive filename filepath (including access path)
  2. Use OS. Stat() to get the file properties and get the pure filename (remove the access path)
  3. Initiate the connection server request actively, and close the connection at the end.
  4. Send filename to receiver conn.write()
  5. Read the confirmation data sent back by the receiver conn.read()
  6. Judge whether it is “OK”. If so, encapsulate the sendfile() function to send the contents of the file. Parameters filepath and conn
  7. Read only open file, close file at the end
  8. Read the local file circularly, read EOF, and finish reading.
  9. Send the read content to the receiver (server) intact conn.write

Sender Code:

package main

import (
    "fmt"
    "io"
    "net"
    "os"
)
func sendFile(conn net.Conn, filePath string) {
    //Read only open file
    file, err := os.Open(filePath)
    if err != nil {
        FMT. Printf ("OS. Open() function execution error, error is:% v \ n", ERR)
        return
    }
    defer file.Close()

    buf := make([]byte, 4096)
    for {
        //Read the data from the local file and write it to the network receiver. How much to read, how much to write
        n, err := file.Read(buf)
        if err != nil {
            if err == io.EOF {
                FMT. Printf ("sending file completed \ n")
            } else {
                FMT. Printf ("file. Read() method execution error, error is:% v \ n", ERR)
            }
            return
        }
        //Write to network socket
        _, err = conn.Write(buf[:n])
    }
}

func main() {

    //Get command line parameters
    list := os.Args

    if len(list) != 2 {
        FMT. Printf ("format: go run XXX. Go filename \ n")
        return
    }

    //Absolute path to extract file
    path := list[1]

    //Get file properties
    fileInfo, err := os.Stat(path)
    if err != nil {
        FMT. Printf ("OS. Stat() function execution error, error is:% v \ n", ERR)
        return
    }

    //Initiate connection request actively
    conn, err := net.Dial("tcp", "127.0.0.1:8000")
    if err != nil {
        FMT. Printf ("net. Dial() function execution error, error is:% v \ n", ERR)
        return
    }
    defer conn.Close()

    //Send file name to receiver
    _, err = conn.Write([]byte(fileInfo.Name()))

    //Read server postback data
    buf := make([]byte, 4096)
    n, err := conn.Read(buf)
    if err != nil {
        FMT. Printf ("conn.read (buf) method execution error, error is:% v \ n", ERR)
        return
    }

    if string(buf[:n]) == "ok" {
        //Write file content to server -- with conn
        sendFile(conn, path)
    }
}

Recommended Today

Python basics Chinese series tutorial · translation completed

Original: Python basics Python tutorial Protocol: CC by-nc-sa 4.0 Welcome anyone to participate and improve: a person can go very fast, but a group of people can go further. Online reading Apache CN learning resources catalog introduce Seven reasons to learn Python Why Python is great Learn Python introduction Executing Python scripts variable character string […]