普通网友 2017-10-05 06:49
浏览 68
已采纳

golang net.Conn没有可用数据属性

I am new to go. I have been coding in C# but I need server as well. So I have written a server:

func ServeToClient(client net.Conn) {
for {
    fmt.Fprintln(client,"Serving you!")
    buffer:=make([]byte,1024)
    _, err :=bufio.NewReader(client).Read(buffer)
    if err!=nil{
        fmt.Println(err)
        client.Close()
        fmt.Println("Disconnected duet to the error: ",err.Error())
        return
    }
    data := string(buffer)
    fmt.Println(data)
    command := data[0:2]
    i,err := strconv.Atoi(command)
    if err!=nil {
        fmt.Println(err)
        return
    }
}

But it sees the data as :

{"id":"009","username":"Bungler"}??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

And I guess it is owing to excess of byte byte array(it is in 1024 length). Is there any property (like in C# Socket.Availabe) to create my byte array properly?

  • 写回答

2条回答 默认 最新

  • 普通网友 2017-10-05 07:08
    关注

    According with Read() you're ignoring the number of bytes read into variable buffer, on this line:

    _, err := bufio.NewReader(client).Read(buffer)

    Just add a new variable n to store the number of bytes:

    n, err := bufio.NewReader(client).Read(buffer)

    and then you can take only that number of bytes from your buffer that has length of 1024:

    data := string(buffer[:n])

    Edit:

    Other alternatives:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dongman5539 2017-10-05 07:12
    关注

    Adding to Yandry Pozo's answer: n could be more than 1024 or maybe you don't get the whole message in one call to Read. (Over a network that is all possible.)

    So to get a reliable communication protocol you should define some message format, where the receiver can determine, wether the message is complete.

    For example you could do a simple form of framing and send the length of the message in the first 4 bytes. You could then read until you get 4 bytes and then call Read repeatedly, until you got the whole message.

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 webapi的部署(标签-服务器)
  • ¥20 怎么加快手机软件内部计时的时间(关键词-日期时间)
  • ¥15 C语言除0问题的检测方法
  • ¥15 为什么四分管的内径有的是16mm有的15mm,四分不应该是12.7mm吗
  • ¥15 macos13下 ios交叉编译的问题
  • ¥15 bgz压缩文件怎么打开
  • ¥15 封装dll(引入了pcl的点云设计库)
  • ¥30 关于#开发语言#的问题:我需要在抄板的基础上再抄板抄程序,根据RDA8851CM基础上开发
  • ¥15 oracle 多个括号,怎么删除指定的括号及里面的内容?
  • ¥15 小新14API2019想用bios调风扇