This commit is contained in:
2020-02-11 10:50:11 +08:00
parent dc7e6db1a0
commit f30d42e130
2 changed files with 39 additions and 40 deletions
+18 -17
View File
@@ -1,6 +1,7 @@
package notify
import (
"context"
"net"
"strings"
"time"
@@ -13,14 +14,14 @@ type StarNotifyC struct {
Connc net.Conn
clientSign map[string]chan string
// FuncLists 当不使用channel时,使用此记录调用函数
FuncLists map[string]func(CMsg)
clientStopSign chan int
defaultFunc func(CMsg)
FuncLists map[string]func(CMsg)
stopSign context.Context
cancel context.CancelFunc
defaultFunc func(CMsg)
// Stop 停止信 号
Stop chan int
// UseChannel 是否使用channel作为信息传递
UseChannel bool
notifychan chan int
isUDP bool
// Queue 是用来处理收发信息的简单消息队列
Queue *starainrt.StarQueue
@@ -35,12 +36,14 @@ type CMsg struct {
}
func (star *StarNotifyC) starinitc() {
star.stopSign, star.cancel = context.WithCancel(context.Background())
star.Queue = starainrt.NewQueue()
star.FuncLists = make(map[string]func(CMsg))
star.UseChannel = true
star.clientStopSign, star.notifychan, star.Stop = make(chan int, 1), make(chan int, 3), make(chan int, 5)
star.Stop = make(chan int, 5)
star.clientSign = make(map[string]chan string)
star.Online = false
star.Queue.RestoreDuration(time.Second * 2)
}
// Notify 用于获取一个通知
@@ -77,10 +80,8 @@ func NewNotifyC(netype, value string) (*StarNotifyC, error) {
}
go star.cnotify()
go func() {
<-star.clientStopSign
star.notifychan <- 2
<-star.stopSign.Done()
star.Connc.Close()
star.Stop <- 0
star.Online = false
return
}()
@@ -93,8 +94,7 @@ func NewNotifyC(netype, value string) (*StarNotifyC, error) {
}
if err != nil {
star.Connc.Close()
star.Stop <- 1
star.notifychan <- 3
star.ClientStop()
//star, _ = NewNotifyC(netype, value)
star.Online = false
return
@@ -107,20 +107,20 @@ func NewNotifyC(netype, value string) (*StarNotifyC, error) {
// Send 用于向Server端发送数据
func (star *StarNotifyC) Send(name string) error {
_, err := star.Connc.Write(star.Queue.BuildMessage(name))
_, err := star.Connc.Write(star.Queue.BuildMessage([]byte(name)))
return err
}
// SendValue 用于向Server端发送key-value类型数据
func (star *StarNotifyC) SendValue(name, value string) error {
_, err := star.Connc.Write(star.Queue.BuildMessage(name + "||" + value))
_, err := star.Connc.Write(star.Queue.BuildMessage([]byte(name + "||" + value)))
return err
}
func (star *StarNotifyC) cnotify() {
for {
select {
case <-star.notifychan:
case <-star.stopSign.Done():
return
default:
}
@@ -129,12 +129,12 @@ func (star *StarNotifyC) cnotify() {
time.Sleep(time.Millisecond * 20)
continue
}
if data.Msg == "b612ryzstop" {
star.clientStopSign <- 0
if string(data.Msg) == "b612ryzstop" {
star.ClientStop()
star.Online = false
return
}
strs := strings.SplitN(data.Msg, "||", 2)
strs := strings.SplitN(string(data.Msg), "||", 2)
if len(strs) < 2 {
continue
}
@@ -158,7 +158,8 @@ func (star *StarNotifyC) ClientStop() {
if star.isUDP {
star.Send("b612ryzstop")
}
star.clientStopSign <- 1
star.cancel()
star.Stop <- 1
}
// SetNotify 用于设置关键词的调用函数