dongxu1875 2016-12-20 22:13
浏览 494
已采纳

golang从net.TCPConn读取字节,其中4字节作为消息分隔

I am working on SIP over TCP mock service in golang. Incoming SIP messages are separated by ' ' 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.

  • 写回答

1条回答 默认 最新

  • doumalu9257 2016-12-20 22:49
    关注

    You can either choose to buffer the reads up yourself and split on the 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{'', '
    ', '', '
    '}
        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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘