-
Notifications
You must be signed in to change notification settings - Fork 0
/
SocketClient.h
69 lines (59 loc) · 1.57 KB
/
SocketClient.h
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
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
class SocketClient
{
private:
int PORT;
int sock, valread;
struct sockaddr_in serv_addr;
const char* message;
char buffer[1024];
public:
SocketClient(int _PORT, const char* _message);
~SocketClient();
// setup the address configuration structure
void setAddressConfiguration();
// connect
void connectSocket();
};
SocketClient::SocketClient(int _PORT, const char* _message)
{
PORT = _PORT;
message = _message;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Client Side Socket creation failed. \n");
exit(EXIT_FAILURE);
}
}
SocketClient::~SocketClient()
{
PORT = 3003;
printf("Warning: Moving PORT address to 3003\n");
message = "Hey there 👋, this is the sample message that will be sent from the client to the server";
}
void SocketClient::setAddressConfiguration()
{
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0)
{
printf("\nInvalid address || Address not supported \n");
exit(EXIT_FAILURE);
}
}
void SocketClient::connectSocket() {
if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)))
{
printf("\n Connection Failed \n");
exit(EXIT_FAILURE);
}
send(sock, message, strlen(message), 0);
printf("Message sent\n");
valread = read(sock, buffer, 1024);
printf("%s\n", buffer);
}