获取文件信息需要用到os. Stat接口,发送文件前开启接收者(服务端),启动客户端先发送文件名给接收者,接收者收到文件名返回确认信息"ok",才读取本地文件 发送给接收者。
发送者:
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]) } }
接收者:
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 } } }
以上就是分享golang实现文件传输小demo的详细内容,更多请关注其它相关文章!