简体   繁体   中英

golang read bytes from net.TCPConn with 4 bytes as message separation

I am working on SIP over TCP mock service in golang. Incoming SIP messages are separated by '\\r\\n\\r\\n' sequence (I do not care about SDP for now). I want to extract message based on that delimiter and send it over to the processing goroutine. Looking through golang standard libraries I see no trivial way of achieving it. There seems to be no one shop stop in io and bufio packages. Currently I see two options of going forward (bufio):

  1. *Reader.ReadBytes function with '/r' set as the delimiter. Further processing is done by using ReadByte function and comparing it sequentially with each byte of the delimiter and unreading them if necessary (which looks quite tedious)

  2. Using Scanner with a custom split function, which does not look too trivial as well.

I wonder whether there are any other better options, functionality seems so common that it is hard to believe that it is not possible to just define delimiter for tcp stream and extract messages from it.

You can either choose to buffer the reads up yourself and split on the \\r\\n\\r\\n delimiter, or let a bufio.Scanner do it for you. There's nothing onerous about implementing a scanner.SplitFunc , and it's definitely simpler than the alternative. Using bufio.ScanLines as an example, you could use:

scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
    delim := []byte{'\r', '\n', '\r', '\n'}
    if atEOF && len(data) == 0 {
        return 0, nil, nil
    }
    if i := bytes.Index(data, delim); i >= 0 {
        return i + len(delim), data[0:i], nil
    }
    if atEOF {
        return len(data), data, nil
    }
    return 0, nil, nil
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM