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

112 lines
2.2 KiB
Go

// Package notify is a package which provide common tcp/udp/unix socket service
package notify
import (
"net"
"time"
"b612.me/starainrt"
)
// Queue 是用来处理收发信息的简单消息队列
var Queue *starainrt.StarQueue
// FuncLists 记录了被通知项所记录的函数
var FuncLists map[string]func(NetMsg) string
var serverStopSign chan int
var notifychan chan int
// NetMsg 指明当前被通知的关键字
type NetMsg struct {
Conn net.Conn
key string
}
// Send 用于向client端发送数据
func (nmsg *NetMsg) Send(msg string) error {
_, err := nmsg.Conn.Write(Queue.BuildMessage(nmsg.key + "||" + msg))
return err
}
func init() {
serverStopSign, notifychan = make(chan int), make(chan int)
Queue = starainrt.NewQueue()
FuncLists = make(map[string]func(NetMsg) string)
}
// NewNotifyS 开启一个新的Server端通知
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
}
// SetNotify 用于设置通知关键词和调用函数
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))
}
}
}
// ServerStop 用于终止Server端运行
func ServerStop() {
serverStopSign <- 0
}