| 368 | } |
| 369 | |
| 370 | func (n *server) eventDispatch() { |
| 371 | var wg sync.WaitGroup |
| 372 | wg.Add(1) |
| 373 | go func() { |
| 374 | defer wg.Done() |
| 375 | n.members.Listen(n.ctx, n.peersEvent) |
| 376 | }() |
| 377 | |
| 378 | subscriptions := make(map[int]chan discover.P2PEvent) |
| 379 | subID := 1 |
| 380 | L: |
| 381 | for { |
| 382 | select { |
| 383 | case e, ok := <-n.peersEvent: |
| 384 | if ok { |
| 385 | for _, eventCh := range subscriptions { |
| 386 | select { |
| 387 | case <-n.ctx.Done(): |
| 388 | case eventCh <- e: |
| 389 | } |
| 390 | } |
| 391 | } |
| 392 | case sub, ok := <-n.subscribeEvent: |
| 393 | if ok { |
| 394 | sub.eventCh = make(chan discover.P2PEvent) |
| 395 | sub.subID = subID |
| 396 | subID++ |
| 397 | subscriptions[sub.subID] = sub.eventCh |
| 398 | select { |
| 399 | case <-n.ctx.Done(): |
| 400 | case sub.replyCh <- sub: |
| 401 | } |
| 402 | } |
| 403 | case subID, ok := <-n.unscribeEvent: |
| 404 | if ok { |
| 405 | close(subscriptions[subID]) |
| 406 | delete(subscriptions, subID) |
| 407 | } |
| 408 | case <-n.ctx.Done(): |
| 409 | n.members.Leave() |
| 410 | for _, eventCh := range subscriptions { |
| 411 | close(eventCh) |
| 412 | } |
| 413 | break L |
| 414 | } |
| 415 | } |
| 416 | wg.Wait() |
| 417 | return |
| 418 | } |
| 419 | |
| 420 | func (n *server) messageDispatch() { |
| 421 | subscriptions := make(map[string]chan P2PMessage) |