liuxiaolong
2020-04-20 a4ea6380ed70468b1bbaca0328a65686960fcd52
server.go
@@ -1,7 +1,9 @@
package gopherdiscovery
import (
   "encoding/json"
   "log"
   "sync"
   "time"
   "golang.org/x/net/context"
@@ -49,6 +51,9 @@
   nodes StringSet
   // publisher, we are going to publish the changes of the set here
   publisher *Publisher
   svInfo map[string][]byte
   svLock sync.RWMutex
}
type Publisher struct {
@@ -138,6 +143,7 @@
   var err error
   var msg []byte
   var responses StringSet
   var si ServiceInfo
   err = d.sock.Send([]byte("are you ok?"))
   if err != nil {
@@ -146,6 +152,7 @@
   }
   responses = NewStringSet()
   d.services.svInfo = make(map[string][]byte, 0)
   for {
      msg, err = d.sock.Recv()
      if err != nil {
@@ -155,7 +162,12 @@
            return
         }
      } else {
         responses.Add(string(msg))
         if  json.Unmarshal(msg, &si) == nil {
            responses.Add(si.ServiceId)
            d.services.svLock.Lock()
            d.services.svInfo[si.ServiceId] = si.Info
            d.services.svLock.Unlock()
         }
      }
   }
}
@@ -211,6 +223,7 @@
   s := &Services{
      nodes:     NewStringSet(),
      publisher: publisher,
      svInfo: make(map[string][]byte, 0),
   }
   return s
@@ -230,6 +243,20 @@
   //s.publisher.Publish(s.nodes.ToSlice())//publish nodes changed
}
func (d *DiscoveryServer) AliveNodes() StringSet {
   return d.services.nodes
}
func (d *DiscoveryServer) SvInfo() map[string][]byte {
   d.services.svLock.Lock()
   defer d.services.svLock.Unlock()
   m := make(map[string][]byte)
   for k,v := range d.services.svInfo {
      m[k] = v
   }
   return m
}
func (d *DiscoveryServer) PublishMsg(msg string) {
   d.services.publisher.Publish([]byte(msg))
}