main.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include "Network.h"
  4. int kbhit()
  5. {
  6. struct timeval tv;
  7. fd_set fds;
  8. tv.tv_sec = 0;
  9. tv.tv_usec = 0;
  10. FD_ZERO(&fds);
  11. FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0
  12. select(STDIN_FILENO+1, &fds, NULL, NULL, &tv);
  13. return FD_ISSET(STDIN_FILENO, &fds);
  14. }
  15. int main(int argc, char **argv) {
  16. //UDP
  17. /*int l = 10;
  18. char c[l];
  19. UDP::sendTo("127.0.0.1", 9995, "quit");
  20. bool b = UDP::receiveFrom(9999, c, 10);
  21. std::cout << std::boolalpha << b << " " << c << std::endl;*/
  22. srand(time(0));
  23. if(argc > 1){
  24. TCPClient socket;
  25. std::string name = std::string(argv[1]), msg;
  26. bool connected = socket.connect("127.0.0.1", 9995, name);
  27. std::cout << "connection established: " << std::boolalpha << connected << std::endl;
  28. while(socket.isConnected()){
  29. if(kbhit()){
  30. std::getline(std::cin, msg);
  31. socket.send({msg});
  32. }
  33. msg = (std::string)socket.receive();
  34. if(msg != "") std::cout << "serveur: " << msg << std::endl;
  35. }
  36. }else{
  37. int n = 2;
  38. TCPServer socket(9995, n, true);
  39. bool hosting = socket.host();
  40. std::cout << "host: " << std::boolalpha << hosting << std::endl;
  41. if(hosting){
  42. //while(socket.getNbConnected() < 2) std::this_thread::sleep_for(std::chrono::milliseconds(1));
  43. /*while(true){
  44. std::string msg = socket.receive(), name = socket.getName();
  45. if(msg != "" || name != "") std::cout << "from:" << name << " (" << msg.size() << "): " << msg << std::endl;
  46. }*/
  47. bool stop = false;
  48. std::string msg;
  49. do{
  50. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  51. if(kbhit()){
  52. std::getline(std::cin, msg);
  53. for(int i = 0;i<socket.getNbConnected();i++) socket[i].send({msg});
  54. }
  55. for(auto name : socket.namesList()){
  56. msg = (std::string)socket(name).receive();
  57. if(msg != "") std::cout << name << ": " << msg << std::endl;
  58. if(msg == "stop") stop = true;
  59. }
  60. }while(!stop);
  61. }
  62. }
  63. return 0;
  64. }