|
|
|
package notify
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
var connc net.Conn
|
|
|
|
|
|
|
|
var clientSign map[string]chan string
|
|
|
|
var clientStopSign chan int
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
clientStopSign = make(chan int)
|
|
|
|
clientSign = make(map[string]chan string)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Notify 用于获取一个通知
|
|
|
|
func Notify(key string) chan string {
|
|
|
|
if _, ok := clientSign[key]; !ok {
|
|
|
|
ch := make(chan string, 5)
|
|
|
|
clientSign[key] = ch
|
|
|
|
}
|
|
|
|
return clientSign[key]
|
|
|
|
}
|
|
|
|
|
|
|
|
func store(key, value string) {
|
|
|
|
if _, ok := clientSign[key]; !ok {
|
|
|
|
ch := make(chan string, 5)
|
|
|
|
ch <- value
|
|
|
|
clientSign[key] = ch
|
|
|
|
return
|
|
|
|
}
|
|
|
|
clientSign[key] <- value
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewNotifyC 用于新建一个Client端进程
|
|
|
|
func NewNotifyC(netype, value string) error {
|
|
|
|
var err error
|
|
|
|
connc, err = net.Dial(netype, value)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
go cnotify()
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-clientStopSign:
|
|
|
|
connc.Close()
|
|
|
|
break
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
buf := make([]byte, 8192)
|
|
|
|
n, err := connc.Read(buf)
|
|
|
|
Queue.ParseMessage(buf[0:n], connc)
|
|
|
|
if err != nil {
|
|
|
|
connc.Close()
|
|
|
|
notifychan <- 0
|
|
|
|
go NewNotifyC(netype, value)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send 用于向Server端发送数据
|
|
|
|
func Send(name string) error {
|
|
|
|
_, err := connc.Write(Queue.BuildMessage(name))
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func cnotify() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-clientStopSign:
|
|
|
|
break
|
|
|
|
case <-notifychan:
|
|
|
|
break
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
data, err := Queue.RestoreOne()
|
|
|
|
if err != nil {
|
|
|
|
time.Sleep(time.Millisecond * 20)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
strs := strings.SplitN(data.Msg, "||", 2)
|
|
|
|
if len(strs) < 2 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
go store(strs[0], strs[1])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ClientStop 终止client端运行
|
|
|
|
func ClientStop() {
|
|
|
|
clientStopSign <- 0
|
|
|
|
}
|