ClientServerProject/client.cpp

84 lines
1.8 KiB
C++
Raw Normal View History

2021-02-09 23:02:05 -05:00
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <queue>
#define max_buffer 1024
#define PORT 666
#define SOCKET int
std::queue<std::string> message_queue_{};
auto ufnk(const SOCKET socket)->std::string
{
if (!message_queue_.empty())
{
auto message = message_queue_.front();
message_queue_.pop();
return message;
}
std::string data;
char message_buffer[max_buffer] = { 0 };
auto length = max_buffer;
while (length == max_buffer)
{
length = ::recv(socket, message_buffer, max_buffer, 0);
for (auto i = 0; i < length; ++i)
if(message_buffer[i]) /*append until null.*/
{
data += message_buffer[i];
}
else
{
message_queue_.push(data);
data.clear();
}
}
if (message_queue_.empty())
return "";
return ufnk(socket); //recurse.
}
int main(int argc, char const *argv[])
{
int sock = 0, valread = 1;
struct sockaddr_in serv_addr;
char *hello = "4";
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
send(sock , hello , strlen(hello)+1 , 0 );
printf("sent date command\n");
while(true)
{
auto text = ufnk(sock);
if (text == "")
break;
printf("%s\n", text.c_str());
}
return 0;
}