123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- #include "clientwriter.h"
- ClientWriter::ClientWriter() {
- buf = new char[65536];
- host_ip = new char[48];
- strcpy(host_ip, "127.0.0.1");
- }
- ClientWriter::~ClientWriter() {
- delete[] buf;
- delete[] host_ip;
- }
- int ClientWriter::exec() {
- if (!createSocket()) {
- return -1;
- }
- sendMessage("writer");
- std::string message;
- std::cout << "Please, enter message to send: ";
- while (std::cin >> message) {
- sendMessage(message);
- std::cout << "Please, enter message to send: ";
- }
- std::cout << "Client: exiting;" << std::endl;
- return 0;
- }
- bool ClientWriter::createSocket() {
- sockd = socket(AF_INET, SOCK_STREAM, 0);
- if (sockd == -1) {
- std::cout << "Client: Error: cannot create socket!" << std::endl;
- return false;
- }
- struct sockaddr_in addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_port = htons(port);
- // Convert IPv4 and IPv6 addresses from text to binary form
- if(inet_pton(AF_INET, host_ip, &addr.sin_addr) <= 0)
- {
- printf("\nInvalid address/Address not supported \n");
- return false;
- }
- if (connect(sockd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
- {
- printf("Client: Error: Connection Failed\n");
- return false;
- }
- return true;
- }
- void ClientWriter::sendMessage(std::string message) {
- send(sockd, message.c_str(), message.length(), 0);
- }
- std::string ClientWriter::receiveMessage() {
- memset(buf, 0, 65536);
- recv(sockd, buf, 65536, 0);
- return std::string(buf);
- }
|