| 551 | } |
| 552 | |
| 553 | void Loop() |
| 554 | { |
| 555 | while (loop) |
| 556 | { |
| 557 | { |
| 558 | // apply pending |
| 559 | std::lock_guard<std::mutex> g(mutexPending); |
| 560 | for (auto& p : pending) |
| 561 | { |
| 562 | if (p.second & OpClose) |
| 563 | sockets.erase(p.first); |
| 564 | else |
| 565 | sockets[p.first] = p.second; |
| 566 | } |
| 567 | pending.clear(); |
| 568 | } |
| 569 | |
| 570 | fd_set setwrite, setread; |
| 571 | FD_ZERO(&setwrite); |
| 572 | FD_ZERO(&setread); |
| 573 | |
| 574 | int maxfd = 0; |
| 575 | for (auto& socket : sockets) |
| 576 | { |
| 577 | if (socket.first->socket > maxfd) |
| 578 | maxfd = socket.first->socket; |
| 579 | if (socket.second & OpRead) |
| 580 | FD_SET(socket.first->socket, &setread); |
| 581 | if (socket.second & OpWrite) |
| 582 | FD_SET(socket.first->socket, &setwrite); |
| 583 | } |
| 584 | FD_SET(wakeupfds[0], &setread); // wakeup fd |
| 585 | |
| 586 | struct timeval timeout = { 0 }; |
| 587 | timeout.tv_sec = 1; |
| 588 | timeout.tv_usec = 0; |
| 589 | |
| 590 | if (::select(maxfd + 1, &setread, &setwrite, nullptr, &timeout) > 0) |
| 591 | { |
| 592 | if (FD_ISSET(wakeupfds[0], &setread)) |
| 593 | { |
| 594 | char buf[256]; |
| 595 | while (true) // 确保读完所有的wakeup消息。 |
| 596 | { |
| 597 | if (::recv(wakeupfds[0], buf, sizeof(buf), 0) < sizeof(buf)) |
| 598 | break; |
| 599 | } |
| 600 | } |
| 601 | for (auto& socket : sockets) |
| 602 | { |
| 603 | try |
| 604 | { |
| 605 | if (FD_ISSET(socket.first->socket, &setread)) |
| 606 | socket.first->OnRecv(); |
| 607 | if (FD_ISSET(socket.first->socket, &setwrite)) |
| 608 | socket.first->OnSend(); |
| 609 | } |
| 610 | catch (std::exception& ex) |