duan198727 2014-05-21 06:44
浏览 22

Go中读取整体网络PDU的方法

I am developing a simple Go server program which receives client's request and process it. And the code is simplified as this:

package main

import (
    "fmt"
    "net"
    "os"
)

const (
    pduLen = 32
)

func checkError(err error) {
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

func main() {
    var buffer [4096]byte
    var count int

    conn, err := net.Dial("tcp", fmt.Sprintf("%s:%s", os.Args[1], os.Args[2]))
    checkError(err)

    for count < pduLen {
        n, err := conn.Read(buffer[count:])
        checkError(err)
        count += n
    }
    ......

}

I assume every request's length is 32 bytes (just an example). Because the TCP is a stream protocol, I need to use a loop to check whether an integral PDU is read:

for count < pduLen {
    n, err := conn.Read(buffer[count:])
    checkError(err)
    count += n
}

Is there any method to assure that an integral PDU is read? Personally, I think the loop code is a little ugly.

  • 写回答

2条回答 默认 最新

  • doutangshuan6473 2014-05-21 07:35
    关注

    It can depend on the exact nature of the PDU you are receiving, but this example will look for the size, and then read everything (using io.ReadFul()).

    func read(conn net.Conn, key string) string {
      fmt.Fprintf(conn, GenerateCommand(OP_GET, key))
      if verify(conn) {
        var size uint16
        binary.Read(conn, binary.LittleEndian, &size)
        b := make([]byte, size)
        // _, err := conn.Read(b)
        _, err := io.ReadFull(conn, b)
        if err == nil {
          return string(b)
        }
      }
      return ""
    }
    
    func verify(conn net.Conn) bool {
      b := make([]byte, 1)
      conn.Read(b)
      return b[0] == ERR_NO_ERROR
    }
    

    Used in:

    conn, err := net.Dial("tcp", ":12345")
    if err != nil {
      t.Error(err)
    }
    write(conn, "foo", "bar")
    if !verify(conn) {
      t.Error("Bad write!")
    }
    if r := read(conn, "foo"); r != "bar" {
      t.Errorf("Bad read! Got %v", r)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?