doupao6698 2017-04-21 04:38
浏览 65
已采纳

缓冲读取器VS listenUDP

If I am "infinitely" using the buffered reader to wait for messages from the server, is this not pretty much the same as using ListenUDP?

But if use ListenUDP, then I've created another server ...

Is it bad practice to "infinitely" collect from this buffered reader or is that in general how it is done with the client?

client.go

package main

import (
    "fmt"
    "time"
    "net"
    "sync"
    "bufio"
)

func xyz(conn net.Conn, p []byte) {
    rd := bufio.NewReader(conn)
    for {
        fmt.Printf("line
")
        _, err := rd.Read(p)
        if err == nil {
            fmt.Printf("SERVER : %s
", p)
        } else {
            fmt.Printf("Some error %v
", err)
        }
    }
}

func main() {
    var wg = &sync.WaitGroup{}
    p :=  make([]byte, 2048)
    conn, err := net.Dial("udp", "127.0.0.1:1234")
    if err != nil {
        fmt.Printf("Some error %v", err)
        return
    }
    wg.Add(1)
    go xyz(conn, p)
    time.Sleep(2 * time.Second);
    fmt.Fprintf(conn, "Give me a hash to work on ...")
    time.Sleep(4 * time.Second)
    wg.Wait()
}

server.go

package main

import (
    "fmt"
    "net"
)

func sendResponse(conn *net.UDPConn, addr *net.UDPAddr, hash string) {
    _,err := conn.WriteToUDP([]byte("Hello, here is the hash  - " + hash), addr)
    if err != nil {
        fmt.Printf("Couldn't send response %v", err)
    }
}

func main() {
    hash := "36";
    p := make([]byte, 2048)
    addr := net.UDPAddr{
        Port: 1234,
        IP: net.ParseIP("127.0.0.1"),
    }
    ser, err := net.ListenUDP("udp", &addr)
    if err != nil {
        fmt.Printf("Some error %v
", err)
        return
    }
    for {
        _, remoteaddr, err := ser.ReadFromUDP(p)
        fmt.Printf("CLIENT : %v : %s
", remoteaddr, p)
        if err !=  nil {
            fmt.Printf("Some error  %v", err)
            continue
        }
        go sendResponse(ser, remoteaddr, hash)
    }
}
  • 写回答

1条回答 默认 最新

  • dqsa17330 2017-04-21 14:32
    关注

    You don't need to use a bufio.Reader to read from a net.Conn, and in the case of a UDP connection, it can only cause problems.

    UDP is not stream based, so you will always need to read each individual datagram. In the best case a bufio.Reader is just buffering the data one extra time, in the worst case the buffer is near full and you only get a partial read, losing data. You also can no longer differentiate the messages once multiple datagrams have been buffered unless they contain additional framing.

    Just read directly from the net.Conn into your []byte:

    for {
        n, err := conn.Read(p)
        fmt.Printf("SERVER : %s
    ", p[:n])
        if err != nil {
            fmt.Printf("Some error %v
    ", err)
            return
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建