Exemplo n.º 1
0
func NewRouter(key *utils.PrivateKey, logger *log.Logger, config utils.Config) (*Router, error) {
	exit := make(chan int)
	listener, err := getOpenPortConn(config)
	if err != nil {
		return nil, err
	}

	logger.Info("Node ID: %s", key.Digest().String())
	logger.Info("Node Socket: %v", listener.Addr())

	ns := utils.GlobalNamespace
	id := utils.NewNodeID(ns, key.Digest())

	r := Router{
		id:       id,
		listener: listener,
		key:      key,
		sessions: make(map[utils.NodeID]*session),
		mainDht:  dht.NewDHT(10, id, id, listener.RawConn, logger),
		groupDht: make(map[utils.NodeID]*dht.DHT),

		receivedPackets: make(map[[20]byte]int),

		logger: logger,
		recv:   make(chan Message, 100),
		send:   make(chan internal.Packet, 100),
		exit:   exit,
	}

	go r.run()
	return &r, nil
}
Exemplo n.º 2
0
func (p *Router) Join(group utils.NodeID) error {
	if p.getGroupDht(group) == nil {
		d := dht.NewDHT(10, p.ID(), group, p.listener.RawConn, p.logger)
		for _, n := range p.mainDht.LoadNodes(group.String()) {
			if !n.ID.Match(p.id) {
				d.Discover(n.Addr)
			}
		}
		p.dhtMutex.Lock()
		p.groupDht[group] = d
		p.dhtMutex.Unlock()
		p.mainDht.StoreNodes(group.String(), []utils.NodeInfo{
			utils.NodeInfo{ID: p.id, Addr: p.listener.Addr()},
		})
		return nil
	}
	return errors.New("already joined")
}