You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
notify/server.go

102 lines
1.7 KiB
Go

package notify
import (
"net"
"time"
"b612.me/starainrt"
)
var Queue *starainrt.StarQueue
var FuncLists map[string]func(NetMsg) string
var serverStopSign chan int
var notifychan chan int
type NetMsg struct {
Conn net.Conn
key string
}
func (this *NetMsg) Send(msg string) error {
_, err := this.Conn.Write(Queue.BuildMessage(this.key + "||" + msg))
return err
}
func init() {
serverStopSign, notifychan = make(chan int), make(chan int)
Queue = starainrt.NewQueue()
FuncLists = make(map[string]func(NetMsg) string)
}
func NewNotifyS(netype, value string) error {
listener, err := net.Listen(netype, value)
if err == nil {
go notify()
go func() {
for {
select {
case <-serverStopSign:
listener.Close()
break
default:
}
conn, err := listener.Accept()
if err != nil {
continue
}
go func(conn net.Conn) {
for {
select {
case <-serverStopSign:
break
default:
}
buf := make([]byte, 8192)
n, err := conn.Read(buf)
if n != 0 {
Queue.ParseMessage(buf[0:n], conn)
}
if err != nil {
conn.Close()
break
}
}
}(conn)
}
}()
}
return err
}
func SetNotify(name string, data func(NetMsg) string) {
FuncLists[name] = data
}
func notify() {
for {
select {
case <-serverStopSign:
break
case <-notifychan:
break
default:
}
data, err := Queue.RestoreOne()
if err != nil {
time.Sleep(time.Millisecond * 20)
continue
}
if msg, ok := FuncLists[data.Msg]; ok {
sdata := msg(NetMsg{data.Conn.(net.Conn), data.Msg})
if sdata == "" {
continue
}
sdata = data.Msg + "||" + sdata
data.Conn.(net.Conn).Write(Queue.BuildMessage(sdata))
}
}
}
func ServerStop() {
serverStopSign <- 0
}