一、客户端实现方案:
package mainimport ("fmt""io""net""os"
)func sendFile(filePath string, conn net.Conn) {defer conn.Close()// 获取文件名fileInfo, err := os.Stat(filePath)if err != nil {fmt.Println("Error getting file info:", err)return}fileName := fileInfo.Name()// 发送文件名conn.Write([]byte(fileName))// 打开文件并发送文件内容file, err := os.Open(filePath)if err != nil {fmt.Println("Error opening file:", err)return}defer file.Close()_, err = io.Copy(conn, file)if err != nil {fmt.Println("Error copying file content:", err)return}fmt.Printf("File %s sent.\n", fileName)
}func main() {conn, err := net.Dial("tcp", "localhost:8080")if err != nil {fmt.Println("Error connecting to server:", err)return}defer conn.Close()filePath := "C:\\zhangsan.txt" // 替换为实际文件路径sendFile(filePath, conn)
}
二、服务端实现方案:
通过tcp协议的具体应用举例:
package mainimport ("fmt""io""net""os"
)
/*1、
*/
func handleFileTransfer(conn net.Conn) {defer conn.Close()// 读取文件名fileNameBuf := make([]byte, 1024)n, err := conn.Read(fileNameBuf)if err != nil {fmt.Println("Error reading file name:", err)return}fileName := string(fileNameBuf[:n])// 打开文件file, err := os.Create(fileName)if err != nil {fmt.Println("Error creating file:", err)return}defer file.Close()// 从连接中读取文件内容并写入到文件_, err = io.Copy(file, conn)if err != nil {fmt.Println("Error copying file content:", err)return}fmt.Printf("File %s received and saved.\n", fileName)
}func main() {listener, err := net.Listen("tcp", ":8080")if err != nil {fmt.Println("Error:", err)return}defer listener.Close()fmt.Println("File transfer server listening on :8080")for {conn, err := listener.Accept()if err != nil {fmt.Println("Error accepting connection:", err)continue}go handleFileTransfer(conn)}
}