/TGame/TServerGate/Network/DataSession.cpp

http://awoe.googlecode.com/ · C++ · 96 lines · 79 code · 16 blank · 1 comment · 5 complexity · 73736711fa7eb5b785cb5d448bcd380a MD5 · raw file

  1. #include "stdafx.h"
  2. #include "DataSession.h"
  3. #include <iostream>
  4. #include "boost/bind.hpp"
  5. DataSession::DataSession( boost::asio::io_service &svcIO)
  6. :m_theSvcIO(svcIO), m_theSocket(svcIO), m_wpMsgBufferFactory(NULL)
  7. {
  8. }
  9. int
  10. DataSession::getID()const
  11. {
  12. return m_nSesId;
  13. }
  14. void
  15. DataSession::setID(int nID)
  16. {
  17. m_nSesId = nID;
  18. }
  19. boost::asio::ip::tcp::socket&
  20. DataSession::getSocket()
  21. {
  22. return m_theSocket;
  23. }
  24. bool
  25. DataSession::read(MsgBuffer* pStream)
  26. {
  27. if (pStream==NULL)
  28. {
  29. pStream = m_wpMsgBufferFactory->malloc();
  30. }
  31. if (pStream)
  32. {
  33. boost::asio::async_read(m_theSocket,
  34. pStream->prepare(1024),
  35. boost::bind(&DataSession::onInput, this, boost::asio::placeholders::error, pStream));
  36. }
  37. return true;
  38. }
  39. bool
  40. DataSession::write(MsgBuffer* pStream)
  41. {
  42. if (pStream)
  43. {
  44. boost::asio::async_write(m_theSocket,
  45. pStream->data(),
  46. boost::bind(&DataSession::onOutput, this, boost::asio::placeholders::error, pStream));
  47. }
  48. return true;
  49. }
  50. void
  51. DataSession::setDataStreamPool(MsgBufferFactory* pMsgBuffFact)
  52. {
  53. m_wpMsgBufferFactory = pMsgBuffFact;
  54. }
  55. bool
  56. DataSession::onUpdate(const int& nElapse)
  57. {
  58. return true;
  59. }
  60. void
  61. DataSession::onInput(const boost::system::error_code& error, MsgBuffer* pStream )
  62. {
  63. if (!error)
  64. {
  65. read();
  66. }
  67. else
  68. {
  69. std::cout<<"Error!"<<std::endl;
  70. }
  71. }
  72. void
  73. DataSession::onOutput(const boost::system::error_code& error, MsgBuffer* pStream )
  74. {
  75. if (pStream)
  76. {
  77. // recycle
  78. m_wpMsgBufferFactory->free(pStream);
  79. }
  80. }