ServerTcpStatu.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // Created by zx on 22-12-22.
  3. //
  4. #include "ServerTcpStatu.h"
  5. ServerTcpStatu::ServerTcpStatu(){
  6. }
  7. bool ServerTcpStatu::Bind(int port)
  8. {
  9. vector<int> opts = { SO_REUSEPORT, SO_REUSEADDR };
  10. if(setup(port,opts) == 0)
  11. {
  12. exit_=true;
  13. if(thread_accept)
  14. {
  15. if(thread_accept->joinable())
  16. thread_accept->join();
  17. }
  18. if(thread_recv)
  19. {
  20. if(thread_recv->joinable())
  21. thread_recv->join();
  22. }
  23. exit_=false;
  24. thread_accept=new std::thread(&ServerTcpStatu::accept,this);
  25. thread_recv=new std::thread(&ServerTcpStatu::recv,this);
  26. return true;
  27. }
  28. return false;
  29. }
  30. void ServerTcpStatu::SetRecvCallback(RecvCallback callback)
  31. {
  32. recv_callback_=callback;
  33. }
  34. void ServerTcpStatu::accept()
  35. {
  36. while(exit_==false)
  37. {
  38. accepted();
  39. cerr << "Accepted" << endl;
  40. }
  41. }
  42. void ServerTcpStatu::recv()
  43. {
  44. while(exit_==false)
  45. {
  46. vector<descript_socket*> desc;
  47. while(1)
  48. {
  49. desc = getMessage();
  50. for(unsigned int i = 0; i < desc.size(); i++)
  51. {
  52. if( desc[i] )
  53. {
  54. if(recv_callback_!= nullptr)
  55. {
  56. recv_callback_(desc[i]->ip,desc[i]->socket,desc[i]->message);
  57. }
  58. clean(i);
  59. }
  60. }
  61. usleep(1000);
  62. }
  63. }
  64. }
  65. void ServerTcpStatu::Publish(std::string data)
  66. {
  67. for(int i=0;i<num_client;++i)
  68. {
  69. Send(data,i);
  70. }
  71. }