Skip to content

Instantly share code, notes, and snippets.

@schigh
Created March 28, 2019 22:20
Show Gist options
  • Select an option

  • Save schigh/4e321d0b28bd69f58d55d79ecd2d5b6a to your computer and use it in GitHub Desktop.

Select an option

Save schigh/4e321d0b28bd69f58d55d79ecd2d5b6a to your computer and use it in GitHub Desktop.

Revisions

  1. schigh created this gist Mar 28, 2019.
    57 changes: 57 additions & 0 deletions udp.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    package main

    import (
    "bytes"
    "log"
    "net"
    "strings"
    "time"
    )

    func main() {
    // listen to incoming udp packets
    pc, err := net.ListenPacket("udp", ":8130")
    if err != nil {
    log.Fatal(err)
    }
    defer pc.Close()

    for {
    buf := make([]byte, 2048)
    pc.ReadFrom(buf)
    parselines(buf)
    }

    }

    func parselines(b []byte) {
    lines := bytes.Split(b, []byte{'\n'})
    for _, l := range lines {
    parseline(l)
    }
    }

    func parseline(b []byte) {
    parts := bytes.Split(b, []byte{'|', 'h', '|', '#'})
    if len(parts) == 0 {
    return
    }
    if len(parts) == 1 {
    showStat(parts[0], []byte{})
    return
    }
    showStat(parts[0], parts[1])
    }

    func showStat(h, b []byte) {
    sb := strings.Builder{}
    sb.WriteString(time.Now().Format(time.StampMicro) + "\n")
    sb.Write(h)
    s := bytes.Split(b, []byte{','})
    for i := 0; i < len(s); i++ {
    sb.Write([]byte{'\n', '\t'})
    sb.Write(s[i])
    }
    sb.WriteByte('\n')
    println(sb.String())
    }