-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.cpp
More file actions
79 lines (71 loc) · 2.09 KB
/
client.cpp
File metadata and controls
79 lines (71 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "client.h"
TCPClient::TCPClient(const char *serverAddress, int port)
{
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
{
throw std::runtime_error("ERROR - Creating the client socket failed!");
}
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr(serverAddress);
serverAddr.sin_port = htons(port);
}
void TCPClient::connectToServer()
{
if(connect(sockfd, (struct sockaddr*) &serverAddr, sizeof(serverAddr)) == -1)
{
throw std::runtime_error("ERROR - Connecting to the server failed!");
}
std::cout << "Connected to the server (Type Quit. to disconnect)" << std::endl;
}
int TCPClient::getClientSocketFd() const
{
return sockfd;
}
void Communication::sendMessage(int fd, const char *buffer)
{
ssize_t numOfBytes = write(fd, buffer, BUFFER_SIZE);
if(numOfBytes == -1)
{
throw std::runtime_error("ERROR - Writing data to server failed!");
}
}
void Communication::receiveMessage(int fd, char *buffer)
{
ssize_t numOfBytes = read(fd, buffer, BUFFER_SIZE);
if(numOfBytes == -1)
{
throw std::runtime_error("ERROR - Reading data from server failed!");
}
std::cout << "Server: " << buffer << std::endl;
}
int main()
{
try
{
TCPClient client("127.0.0.1", PORT_NUM); // using localhost for testing
client.connectToServer();
Communication comm;
char buffer[BUFFER_SIZE];
while(1)
{
memset(buffer, 0, BUFFER_SIZE);
std::cout << "\t\t\t\tMe: ";
std::cin.getline(buffer, BUFFER_SIZE);
comm.sendMessage(client.getClientSocketFd(), buffer);
if(strncmp("Quit.", buffer, 5) == 0)
{
std::cout << "Disconnected from the server." << std::endl;
break;
}
memset(buffer, 0, BUFFER_SIZE);
comm.receiveMessage(client.getClientSocketFd(), buffer);
}
}
catch(const std::exception &e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
return 0;
}