dongzhuang1923 2014-09-27 01:10
浏览 87
已采纳

在Go中通过套接字发送int64的正确方法

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
}
  • 写回答

3条回答 默认 最新

  • douxie1894 2014-09-27 02:37
    关注

    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) 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址