The correct way to send int64 via socket to go

I am trying to send int64 via TCP to golang, however my recipient prints get a different number than what I sent. What is the right way to do this?

//Buffer on both client and server
buffer := make([]byte, 1024)

//Sender
fileInfo, error := os.Stat(fileName)
if error != nil {
    fmt.Println("Error opening file")
}
var fSize int = int(fileInfo.Size())

connection.Write([]byte(string(fSize)))


//Receiver
connection.Read(buffer)

fileSize := new(big.Int).SetBytes(bytes.Trim(buffer, "\x00")).Int64()
if err != nil {
    fmt.Println("not a valid filesize")
    fileSize = 0
}
+4
source share
3 answers

Using binary.Write/ binary.Read:

//sender
err := binary.Write(connection, binary.LittleEndian, fileInfo.Size())
if err != nil {
    fmt.Println("err:", err)
}

//receiver
var size int64
err := binary.Read(connection, binary.LittleEndian, &size)
if err != nil {
    fmt.Println("err:", err)
}

[]byte(string(fSize)) doesn’t do what you think it does, it treats the number as a Unicode character, it does not return a string representation.

If you need a string representation of a number, use strconv.Itoaif you want the binary representation to use:

num := make([]byte, 8) // or 4 for int32 or 2 for int16
binary.LittleEndian.PutUint64(num, 1<<64-1) 
+6
source

binary.BigEndian binary.LittleEndian :

  var size int64

  // Send

  var buf [8]byte
  binary.BigEndian.PutUint64(buf[:], uint64(size))
  _, err := w.Write(buf[:])

  // Receive

  var buf [8]byte
  _, err := io.ReadFull(r, buf[:])
  if err != nil {
      // handle error
  }
  size = int64(binary.BigEndian.Uint64(buf[:])

binary.Read binary.Write. .

.

 string(fSize)

UTF-8 fSize. . strconv . .

connection.Read(buffer)
buffer = bytes.Trim(buffer, "\x00")

, 0 . . :

n, err := connection.Read(buffer)
buffer = buffer[:n]
+1

You cannot use string () to create from int, you need to use the strconv package .

connection.Write([]byte(strconv.FormatInt(fileInfo.Size(), 10))
0
source

All Articles