Пример #1
0
func New(n node.Node) *defaultRouter {
	evChan := make(chan dispatcher.Event, 10)
	reqList := watch.NewRequestListener()
	w := watch.New(reqList, evChan, 2)

	r := &defaultRouter{
		handlers:        make(map[message.MsgType]handler.Handler),
		from:            n,
		peers:           make(map[string]peer.NodePeer),
		peerIDs:         make(map[peer.ID]bool, 0),
		eventChan:       evChan,
		exit:            make(chan bool),
		watcher:         w,
		requestListener: reqList,
	}

	r.RegisterHandlers(r.Handlers())
	r.RegisterHandlers(w.Handlers())

	return r
}
Пример #2
0
func TestRouterAccept(t *testing.T) {
	r := &defaultRouter{
		handlers:        make(map[message.MsgType]handler.Handler),
		exit:            make(chan bool, 1),
		requestListener: watch.NewRequestListener(),
	}

	hello := &message.Hello{}
	ping := &message.Ping{}
	r.RegisterHandler(hello.MessageType(), fakeHelloHandler)
	r.RegisterHandler(ping.MessageType(), fakePingHandler)

	nodeA := node.Node{Host: "A", Port: 1}
	nodeB := node.Node{Host: "B", Port: 2}
	a, b := net.Pipe()

	c1 := peer.NewAcceptor(a, nodeA)
	c1.Identify(nodeB)
	go c1.Run()

	c1Mirror := peer.NewAcceptor(b, nodeB)
	c1Mirror.Identify(nodeA)
	go c1Mirror.Run()

	go func() {
		for {
			select {
			case <-c1.ResetWatcherChan():
				continue
			case <-c1Mirror.ResetWatcherChan():
				continue
			}
		}
	}()

	r.Accept(c1)

	c1Mirror.SayHello()
	result := <-c1Mirror.ReceiveChan()

	if result.MessageType() != 1 {
		t.Error("Unexpected response type, expected 1 got", result.MessageType())
	}

	id := message.NewId()
	msg := message.Ping{
		Id:   id,
		From: nodeA,
		To:   nodeB,
	}
	c1Mirror.Send(msg)

	result = <-c1Mirror.ReceiveChan()
	if result.MessageType() != 4 {
		t.Error("Unexpected response type, expected 1 got", result.MessageType())
	}

	pong := result.(*message.Pong)
	if pong.Id != id {
		t.Error("Unexpected result Id")
	}
	if pong.From != nodeB {
		t.Error("Unexpected result From")
	}

	r.Exit()
	c1.Exit()
	c1Mirror.Exit()
}