duanjing7298 2018-06-10 09:26
浏览 72
已采纳

Go中如何处理粘性TCP数据包?

I have a tcp server and a client, the server does the following

func providerCallback(conn net.Conn) {
    reader := bufio.NewReader(conn)
    var err error
    for {
        lenbyte, _ := reader.Peek(4)
        reader.Discard(4)
        slen := int(binary.BigEndian.Uint32(lenbyte))
        data, err = reader.Peek(slen)
        process(data)
        reader.Discard(slen)
    }
}

The client seems to send packet faster than process can deal with, therefore I'd like to buffer the requests in bufio and process later.

However, as the size of bufio is fixed(4096, even though I can increase it, it is still fixed), which means I can't manually Reset it because there might be a packet cutting of in the end of bufio, as follows

|normal data... [First 20 bytes of packet P] | [the rest of packet P]

|------------------- size of bufio ------------------|

How can I splice packet that is cut off, and reuse the bufio for later packets?

  • 写回答

1条回答 默认 最新

  • dongxiang3205 2018-06-10 11:41
    关注

    For example,

    import (
        "bufio"
        "encoding/binary"
        "io"
        "net"
    )
    
    func providerCallback(conn net.Conn) error {
        rdr := bufio.NewReader(conn)
        data := make([]byte, 0, 4*1024)
        for {
            n, err := io.ReadFull(rdr, data[:4])
            data = data[:n]
            if err != nil {
                if err == io.EOF {
                    break
                }
                return err
            }
            dataLen := binary.BigEndian.Uint32(data)
            if uint64(dataLen) > uint64(cap(data)) {
                data = make([]byte, 0, dataLen)
            }
            n, err = io.ReadFull(rdr, data[:dataLen])
            data = data[:n]
            if err != nil {
                return err
            }
    
            process(data)
        }
        return nil
    }
    
    func process([]byte) {}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题