Listening to messages from the udp socket, I would like to somehow determine where packets come from and scatter in sessions to get a more detailed report on the received data, I just did it forehead, looking for the current session and recording in its channel, I would like to know if more elegant methods?
full code function
for {
buff := bufPool.Get().([]byte)
size, addr, err := pc.ReadFromUDP(buff[0:])
if err != nil {
done <- err
return
}
switch s, ok := getSession(addr); ok {
case true:
s.buffer <- buff[0:size]
bufPool.Put(buff)
s.expiration = time.Now().Add(time.Duration(time.Second * 10)).UnixNano()
atomic.AddInt64(&s.countMessage, 1)
atomic.AddInt64(&s.len, int64(size))
case false:
s := &session{
id: rand.Int(),
conn: addr,
expiration: time.Now().UnixNano(),
buffer: make(chan []byte, 64),
run: func(wg *sync.WaitGroup, in chan []byte, ip string) {
for b := range in {
var m Message
err := json.Unmarshal(b, &m)
if err != nil {
log.Fatal(err)
continue
}
m.Device_ip = ip
out <- m
}
},
}
wg.Add(1)
s.buffer <- buff[0:size]
bufPool.Put(buff)
atomic.AddInt64(&s.countMessage, 1)
atomic.AddInt64(&s.len, int64(size))
go s.run(&wg, s.buffer, s.conn.IP.String())