clientreader.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "clientreader.h"
  2. ClientReader::ClientReader() {
  3. buf = new char[65536];
  4. host_ip = new char[48];
  5. strcpy(host_ip, "127.0.0.1");
  6. }
  7. ClientReader::~ClientReader() {
  8. delete[] buf;
  9. delete[] host_ip;
  10. }
  11. int ClientReader::exec() {
  12. if (!createSocket()) {
  13. return -1;
  14. }
  15. sendMessage("reader");
  16. std::cout << std::endl;
  17. std::string message;
  18. while ((message = receiveMessage()) != "") {
  19. std::cout << message << std::endl;
  20. }
  21. return 0;
  22. }
  23. bool ClientReader::createSocket() {
  24. sockd = socket(AF_INET, SOCK_STREAM, 0);
  25. if (sockd == -1) {
  26. std::cout << "Client: Error: cannot create socket!" << std::endl;
  27. return false;
  28. }
  29. struct sockaddr_in addr;
  30. memset(&addr, 0, sizeof(addr));
  31. addr.sin_family = AF_INET;
  32. addr.sin_port = htons(port);
  33. // Convert IPv4 and IPv6 addresses from text to binary form
  34. if(inet_pton(AF_INET, host_ip, &addr.sin_addr)<=0)
  35. {
  36. printf("\nInvalid address/Address not supported \n");
  37. return -1;
  38. }
  39. if (connect(sockd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
  40. {
  41. printf("Client: Error: Connection Failed\n");
  42. return false;
  43. }
  44. return true;
  45. }
  46. void ClientReader::sendMessage(std::string message) {
  47. send(sockd, message.c_str(), message.length(), 0);
  48. }
  49. std::string ClientReader::receiveMessage() {
  50. memset(buf, 0, 65536);
  51. recv(sockd, buf, 65536, 0);
  52. return std::string(buf);
  53. }