ASYNC - Prime context ready to read a message header
| 513 | |
| 514 | // ASYNC - Prime context ready to read a message header |
| 515 | void ReadHeader() |
| 516 | { |
| 517 | // If this function is called, we are expecting asio to wait until it receives |
| 518 | // enough bytes to form a header of a message. We know the headers are a fixed |
| 519 | // size, so allocate a transmission buffer large enough to store it. In fact, |
| 520 | // we will construct the message in a "temporary" message object as it's |
| 521 | // convenient to work with. |
| 522 | asio::async_read(m_socket, asio::buffer(&m_msgTemporaryIn.header, sizeof(message_header<T>)), |
| 523 | [this](std::error_code ec, std::size_t length) |
| 524 | { |
| 525 | if (!ec) |
| 526 | { |
| 527 | // A complete message header has been read, check if this message |
| 528 | // has a body to follow... |
| 529 | if (m_msgTemporaryIn.header.size > 0) |
| 530 | { |
| 531 | // ...it does, so allocate enough space in the messages' body |
| 532 | // vector, and issue asio with the task to read the body. |
| 533 | m_msgTemporaryIn.body.resize(m_msgTemporaryIn.header.size); |
| 534 | ReadBody(); |
| 535 | } |
| 536 | else |
| 537 | { |
| 538 | // it doesn't, so add this bodyless message to the connections |
| 539 | // incoming message queue |
| 540 | AddToIncomingMessageQueue(); |
| 541 | } |
| 542 | } |
| 543 | else |
| 544 | { |
| 545 | // Reading form the client went wrong, most likely a disconnect |
| 546 | // has occurred. Close the socket and let the system tidy it up later. |
| 547 | std::cout << "[" << id << "] Read Header Fail.\n"; |
| 548 | m_socket.close(); |
| 549 | } |
| 550 | }); |
| 551 | } |
| 552 | |
| 553 | // ASYNC - Prime context ready to read a message body |
| 554 | void ReadBody() |