Home > Article > Backend Development > Share a small demo of file transfer in golang
The following is a small demo of file transfer in golang from the golang tutorial column. I hope it will be helpful to friends who need it!
To obtain file information, you need to use the os. Stat interface. Before sending the file, open the receiver (server). Start the client and send the file name to the receiver first. The receiver receives the file name and returns the confirmation message "ok" ", before reading the local file and sending it to the recipient.
Sender:
package main import ( "fmt" "io" "net" "os") func main() { fmt.Println("请输入接收者地址(IP:PORT):") var addr string fmt.Scan(&addr) fmt.Println("请输入需要传输的文件:") var path string fmt.Scan(&path) info, errf := os.Stat(path) if errf != nil{ fmt.Println("os.Stat errf =", errf) return } conn, err := net.Dial("tcp", addr) if err != nil{ fmt.Println("net.Dial err =",err) return } defer conn.Close() _, err = conn.Write([]byte(info.Name())) if err != nil{ fmt.Println("conn.Write info.Name err =",err) return } var n int buf := make([]byte, 1024) n, err = conn.Read(buf) if err != nil{ fmt.Println("conn.Read ok err =", err) return } if "ok" == string(buf[:n]){ fmt.Println("ok") SendFile(path, conn) } } func SendFile(path string, conn net.Conn){ file , err := os.Open(path) if err != nil{ fmt.Println("os.Open err =", err) return } defer file.Close() buf := make([]byte, 1024 * 4) for { n, err := file.Read(buf) if err != nil{ if err == io.EOF{ fmt.Println("文件发送完毕") } else{ fmt.Println("file.Read err =",err) } return } if n == 0{ fmt.Println("文件发送完毕") break } conn.Write(buf[:n]) } }
Receiver:
package main import ( "fmt" "io" "net" "os") func main() { fmt.Println("请你的地址(IP:PORT):") var addr string fmt.Scan(&addr) listenner, err := net.Listen("tcp", addr) if err != nil{ fmt.Println("net.Listen err =", err) return } defer listenner.Close() conn, errl := listenner.Accept() if errl != nil{ fmt.Println("listenner.Accept err =", errl) return } var n int buf := make([]byte, 1024) n, err = conn.Read(buf) if err != nil{ fmt.Println("conn.Read fileName err =", err) return } fileName := string(buf[:n]) n, err = conn.Write([]byte("ok")) if err != nil{ fmt.Println("conn.Write ok err =", err) return } RecvFile(fileName, conn) } func RecvFile(fileName string, conn net.Conn){ file , err := os.Create(fileName) if err != nil{ fmt.Println("os.Create err =", err) return } defer file.Close() buf := make([]byte, 1024 * 4) for{ n, err := conn.Read(buf) if err != nil{ if err == io.EOF{ fmt.Println("文件接收完成") } else { fmt.Println("conn.Read err =", err) } return } n, err = file.Write(buf[:n]) if err != nil{ fmt.Println("file.Write err =", err) break } } }
The above is the detailed content of Share a small demo of file transfer in golang. For more information, please follow other related articles on the PHP Chinese website!