我刚开始尝试学习Go,并且试图编写一个小的服务器/客户端应用程序,用于将csv文件从服务器发送到客户端。尝试将结构编码为BigEndian二进制文件时遇到了无效的类型错误。我的结构似乎已经是二进制格式,我不确定为什么会出现以下错误:将二进制缓冲区写入大尾数二进制文件时出错。写入:类型* main.DataPack无效另外,我想在发送文件后保持TCP连接打开,这就是为什么我不使用io.Copy的原因。目前,我正在通过发送'\ x00'字节来触发文件上传的处理:// Serverpackage main import ( "path/filepath" "fmt" "io/ioutil" "net" "os" "encoding/binary" "bytes")type DataPack struct { Length int64 Contents []byte}func main() { absPath, _ := filepath.Abs("./progs.csv") data, _ := ioutil.ReadFile(absPath) fmt.Println("%s",data) tel, err := net.Listen("tcp", "0.0.0.0:23") if err != nil { fmt.Println(err) return } for { conn, err := tel.Accept() if err != nil { break } fmt.Println("above filehandler") go fileHandler(conn) }}func fileHandler(conn net.Conn) { buf := make([]byte, 0) buf = append(buf, '\x00') conn.Write(buf) absPath, _ := filepath.Abs("./progs.csv") file, err := os.Open(absPath) defer file.Close() fi, err := file.Stat() if err != nil { fmt.Println("Fatal error reading file: ", err) } fmt.Println("This is the length of the file: ", fi.Size()) data := &DataPack{Length: fi.Size()} // , Contents: } data.Contents = make([]byte, data.Length) n, err := file.Read(data.Contents) if err != nil { fmt.Println("error reading contents into struct: ", err) } fmt.Println("tried to read file contents: ", n) fmt.Println("DataPack: %+v", data) buf1 := new(bytes.Buffer) err = binary.Write(buf1, binary.BigEndian, &data) if err != nil { fmt.Println("Error writing binary buffer to big endian ", err) } conn.Write(buf1.Bytes()) }
1 回答
- 1 回答
- 0 关注
- 209 浏览
添加回答
举报
0/150
提交
取消