main.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include <glibmm.h>
  2. #include <giomm.h>
  3. #include <list>
  4. #include <iostream>
  5. #include <cassert>
  6. #include "SocketHandler.h"
  7. Glib::RefPtr<Glib::MainLoop> loop;
  8. using namespace Glib;
  9. using namespace Gio;
  10. void go()
  11. {
  12. std::unique_ptr<SocketHandler> s=std::make_unique<SingleRequestSocket>("127.0.0.1",5080);
  13. s->setPatrolCounter(5);
  14. SocketHandlerFactory::get()->push(s);
  15. }
  16. class client
  17. {
  18. public:
  19. client(Glib::RefPtr<Gio::Socket>& l){
  20. me=l->accept();
  21. std::cout << "new client" << std::endl;
  22. Gio::signal_socket().connect(sigc::mem_fun(this,&client::i_handler), me, Glib::IO_IN | Glib::IO_OUT);
  23. Gio::signal_socket().connect(sigc::mem_fun(this,&client::o_handler), me, Glib::IO_HUP | Glib::IO_ERR);
  24. };
  25. ~client(){};
  26. bool i_handler(Glib::IOCondition io_condition)
  27. {
  28. s=me->receive(buf,1023);
  29. buf[s+1]='\0';
  30. std::cout << buf;
  31. me->send("$",2);
  32. return true;
  33. }
  34. bool o_handler(Glib::IOCondition io_condition)
  35. {
  36. std::cout << "kill me" << std::endl;
  37. return false;
  38. }
  39. private:
  40. Glib::RefPtr<Gio::Socket> me;
  41. char buf[1024];
  42. gssize s;
  43. };
  44. Glib::RefPtr<Gio::Socket> socket_l;
  45. std::list<client> queue;
  46. bool io_handler(Glib::IOCondition io_condition)
  47. {
  48. queue.emplace_back(socket_l);
  49. return true;
  50. }
  51. int main()
  52. {
  53. Glib::init();
  54. Gio::init();
  55. setlocale(LC_ALL, "C");
  56. std::cout << "local address" << std::endl;
  57. auto inetAddr=Gio::InetAddress::create ("127.0.0.1");
  58. auto inetsocket=Gio::InetSocketAddress::create(inetAddr,5012);
  59. std::cout << "socket" << std::endl;
  60. socket_l=Gio::Socket::create(Gio::SOCKET_FAMILY_IPV4,Gio::SOCKET_TYPE_STREAM
  61. ,Gio::SOCKET_PROTOCOL_TCP) ;
  62. std::cout << "binding to address" << std::endl;
  63. socket_l->bind(inetsocket,true);
  64. socket_l->listen();
  65. loop = Glib::MainLoop::create();
  66. Gio::signal_socket().connect(sigc::ptr_fun(& io_handler), socket_l, Glib::IO_IN | Glib::IO_OUT);
  67. Glib::signal_timeout().connect_seconds_once(sigc::ptr_fun(&go),5);
  68. loop->run();
  69. }