clientwriter.cpp 1.5 KB

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