gnet-io / gnet-examples

Examples of gnet
MIT License
245 stars 77 forks source link

HTTP 请求 header 和 body 不在同一个包发送的问题 #21

Open panjf2000 opened 1 year ago

panjf2000 commented 1 year ago

Actions I've taken before I'm here

What happened?

在 http demo 程序里面, c.Next(-1) 并没有拉到整个请求信息,而是只读取了 header 信息, body 信息没有读取,这样导致在 buf = buf[headerOffset+bodyLen:] ,数组越界 panic,我再次 c.Next 也拉不到更多内容, 但是在下一次 OnTraffic 回调 ,会把剩余的 body 信息读出来。 另外问一下 c.Next(-1) 需要开发者处理 TCP 的拆包和粘包问题吗?

func (hs *httpServer) OnTraffic(c gnet.Conn) gnet.Action {
    hc := c.Context().(*httpCodec)
    buf, _ := c.Next(-1)

pipeline:
    headerOffset, err := hc.parser.Parse(buf)
    if err != nil {
        c.Write(errMsgBytes)
        return gnet.Close
    }
    hc.appendResponse()
    bodyLen := int(hc.parser.ContentLength())
    if bodyLen == -1 {
        bodyLen = 0
    }
    buf = buf[headerOffset+bodyLen:]
    if len(buf) > 0 {
        goto pipeline
    }

    c.Write(hc.buf)
    hc.buf = hc.buf[:0]
    return gnet.None
}

Major version of gnet

v2

Specific version of gnet

v2.2.7

Operating system

macOS

Relevant log output

image

image

Code snippets (optional)

No response

How to Reproduce

Steps to reproduce the behavior:

  1. 写个 demo 程序
  2. 发送 http 请求
  3. 在 OnTraffic 查看 c.Next(-1)

Does this issue reproduce with the latest release?

It can reproduce with the latest release

panjf2000 commented 1 year ago

Transferred from https://github.com/panjf2000/gnet/issues/464