向客户端发送 CSV 文件服务器

Sending a CSV file Server to Client

我最近刚开始尝试学习 Go,我正在尝试编写一个小型 server/client 应用程序,用于将 csv 文件从服务器发送到客户端。尝试将结构编码为 BigEndian 二进制文件时,我 运行 遇到无效类型错误。我的结构似乎已经是二进制格式,我不确定为什么会收到以下错误:

将二进制缓冲区写入大端时出错 binary.Write:类型无效 *main.DataPack

此外,我想在发送文件后保持 TCP 连接打开,这就是我不使用 io.Copy 的原因。

目前我正在通过发送“\x00”字节来触发文件上传处理:

// Server
package 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())  
}

这是客户

package main

import (
    "log"
    "fmt"
    "net"
    "strings"
    "strconv"
    "bufio"
)

const (
    host = "127.0.0.1"
    port = 23
)

func main() {

addr := strings.Join([]string{host, strconv.Itoa(port)}, ":")
client := NewClient()
var err error

client.socket, err = net.Dial("tcp", addr)
if err != nil {
    log.Println("error setting up socket: %s", err)
}

for {

    m := bufio.NewReader(client.socket)
    b, err := m.ReadByte()
    if err != nil {

        fmt.Println("here is the error: ", err)
    }
    if b == '\x00'{
        fmt.Println("about to receive a file!!!")
        b, _ := m.ReadByte()
        fmt.Println("just got another byte ", b )
    }

} 

log.Printf("Over")

}

为什么会出现错误

访问https://golang.org/pkg/encoding/binary/#Write

Write writes the binary representation of data into w. Data must be a fixed-size value or a slice of fixed-size values, or a pointer to such data.

type DataPack struct { Length int64 Contents []byte }

Contents 不是固定大小的值,因此您遇到了无效类型错误。

如何解决

  1. 转二进制
  2. json
  3. 其他