Files
ct/client.cc
2026-04-15 22:18:32 -05:00

104 lines
2.6 KiB
C++

#include <arpa/inet.h>
#include <netdb.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include "disp.h"
#include "log.h"
#include "public.h"
struct waitClientArgs {
sockaddr_in newSockAddr;
socklen_t newSockAddrSize;
int auxInt; // used in client mode because I didn't want to make another
// struct to keep track of
};
void
closeClient()
{
long e = end1.tv_sec - start1.tv_sec;
gettimeofday(&end1, NULL);
close(clientSocketDescriptor);
puts("********Session********");
printf("Bytes written: %i\n", bytesWritten);
printf("Bytes read: %i\n", bytesRead);
printf("Elapsed time: %ld secs\n", e);
puts("Connection closed.");
}
void *
pollForSever(void *args)
{
int b;
char msg[1024], msgf[1033];
waitClientArgs *aaa = static_cast<waitClientArgs *>(args);
int socketDescriptor = (int)aaa->auxInt;
while (1) {
server_message_loop:
memset(&msg, 0, sizeof(msg)); /* clear buffer */
//bytesRead += recv(socketDescriptor, (char *)&msg, sizeof(msg), 0);
b = recv(socketDescriptor, (char *)&msg, sizeof(msg), 0);
msg[b] = '\0';
bytesRead += b;
if (msg[0] == '\0')
goto server_message_loop;
snprintf(msgf, sizeof(msgf), "Server: %s", msg);
writeToFile(logFileName, msgf);
if (linesInFile(logFileName) > LOG_LENGTH)
linePos++;
displayFile(logFileName, linePos, LOG_LENGTH);
}
return nullptr;
}
void
setupClient()
{
// we need 2 things: ip address and port number, in that order
// if(argc != 3)
//{
// cerr << "Usage: ip_address port" << endl; exit(0);
// } //grab the IP address and port number
// create a message buffer
char msg[1024];
// setup a socket and connection tools
if (IP_ADDRESS == "0.0.0.0")
IP_ADDRESS = "127.0.0.1";
struct hostent *host = gethostbyname(IP_ADDRESS.c_str());
sockaddr_in sendSockAddr;
bzero((char *)&sendSockAddr, sizeof(sendSockAddr));
sendSockAddr.sin_family = AF_INET;
sendSockAddr.sin_addr.s_addr = inet_addr(inet_ntoa(*(struct in_addr *)*host->h_addr_list));
sendSockAddr.sin_port = htons(PORT_NUM);
clientSocketDescriptor = socket(AF_INET, SOCK_STREAM, 0);
// try to connect...
int status =
connect(clientSocketDescriptor, (sockaddr *)&sendSockAddr, sizeof(sendSockAddr));
if (status < 0)
writeToFile(logFileName, "Error connecting to socket!");
writeToFile(logFileName, "Connected to the server!");
int bytesRead, bytesWritten = 0;
struct timeval start1, end1;
gettimeofday(&start1, NULL);
auto *aaa = new waitClientArgs{}; // it looks stupid but it works
aaa->auxInt = clientSocketDescriptor;
int rc = pthread_create(&client_wait_thread, nullptr, pollForSever, aaa);
pthread_detach(client_wait_thread);
}