DataChannelObject.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include "pch.h"
  2. #include "DataChannelObject.h"
  3. namespace unity
  4. {
  5. namespace webrtc
  6. {
  7. DataChannelObject::DataChannelObject(
  8. rtc::scoped_refptr<webrtc::DataChannelInterface> channel, PeerConnectionObject& pc)
  9. : dataChannel(channel)
  10. {
  11. dataChannel->RegisterObserver(this);
  12. }
  13. DataChannelObject::~DataChannelObject()
  14. {
  15. dataChannel->UnregisterObserver();
  16. auto state = dataChannel->state();
  17. if (state == webrtc::DataChannelInterface::kOpen)
  18. {
  19. dataChannel->Close();
  20. }
  21. dataChannel = nullptr;
  22. onClose = nullptr;
  23. onOpen = nullptr;
  24. onMessage = nullptr;
  25. }
  26. void DataChannelObject::OnStateChange()
  27. {
  28. auto state = dataChannel->state();
  29. switch (state)
  30. {
  31. case webrtc::DataChannelInterface::kOpen:
  32. if (onOpen != nullptr)
  33. {
  34. onOpen(this->dataChannel);
  35. }
  36. break;
  37. case webrtc::DataChannelInterface::kClosed:
  38. if (onClose != nullptr)
  39. {
  40. onClose(this->dataChannel);
  41. }
  42. break;
  43. case webrtc::DataChannelInterface::kConnecting:
  44. case webrtc::DataChannelInterface::kClosing:
  45. break;
  46. }
  47. }
  48. void DataChannelObject::OnMessage(const webrtc::DataBuffer& buffer)
  49. {
  50. if (onMessage != nullptr)
  51. {
  52. size_t size = buffer.data.size();
  53. if (onMessage != nullptr)
  54. {
  55. onMessage(this->dataChannel, buffer.data.data(), static_cast<int32_t>(size));
  56. }
  57. }
  58. }
  59. } // end namespace webrtc
  60. } // end namespace unity