Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to send an int64 over a socket in go

Tags:

tcp

go

I'm trying to send a int64 over a TCP in golang, however, my receiver prints gets a different number then what I've sent out. What is the proper way to accomplish 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
}
like image 442
Jonathan Eustace Avatar asked Sep 27 '14 01:09

Jonathan Eustace


1 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 unicode character, it doesn't return the string representation of it.

If you want the string representation of a number, use strconv.Itoa, if you want the binary represention then use:

num := make([]byte, 8) // or 4 for int32 or 2 for int16
binary.LittleEndian.PutUint64(num, 1<<64-1) 
like image 53
OneOfOne Avatar answered Nov 15 '22 04:11

OneOfOne