package main

import (
	"encoding/json"
	log "github.com/donnie4w/go-logger/logger"
	mu "mfw/util"
	"net"
	qu "qfw/util"
	"sync"
)

var (
	udpclient mu.UdpClient
	udpLock   sync.Mutex
)

func InitUdpMsg() {
	port := ":1970"
	udpclient = mu.UdpClient{Local: port, BufSize: 1024}
	udpclient.Listen(processUdpMsg)
	log.Debug("监听~", port)
}

func processUdpMsg(act byte, data []byte, ra *net.UDPAddr) {
	switch act {
	case mu.OP_TYPE_DATA:
		var mapInfo map[string]interface{}
		err := json.Unmarshal(data, &mapInfo)
		if err != nil {
			udpclient.WriteUdp([]byte("err:"+err.Error()), mu.OP_NOOP, ra)
		} else if mapInfo != nil {
			sid, eid := qu.ObjToString(mapInfo["gtid"]), qu.ObjToString(mapInfo["lteid"])
			if sid == "" || eid == "" {
				log.Debug("异常~", sid, "~", eid)
			} else {
				key := sid + "-" + eid + "-" + qu.ObjToString(mapInfo["stype"])
				udpclient.WriteUdp([]byte(key), mu.OP_NOOP, ra)
				udpLock.Lock()
				dealWithHaiNaiData(sid, eid)
				udpLock.Unlock()

			}
		}
	case mu.OP_NOOP: //下个节点回应
		ok := string(data)
		if ok != "" {
			log.Debug("接收~", ok)
		}
	}
}


