-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataSetClient.cpp
78 lines (62 loc) · 2.23 KB
/
DataSetClient.cpp
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
//
// Created by t on 22/12/18.
//
#include "DataSetClient.h"
#include <chrono>
#include <thread>
DataSetClient::DataSetClient(string ipAddress, int port, SymbolsTable *symbols) {
try {
//int portno;
ssize_t n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
/* Create a socket point */
this->sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
throw "socket creation failed";
}
server = gethostbyname(ipAddress.c_str());
if (server == NULL) {
throw "bad host name";
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons((uint16_t)port);
/* Now connect to the server */
while (connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
sleep(1);
}
//cout << "client accepted" << endl;
//loop to send to simulator
while (true) {
//get a message for the simulator
pair<string, double> message = symbols->getMessage();
//check validity and send if real message
if (!(message.first == "0" && message.second == 0)) {
memset(buffer, 0, 256);
string str = "set " + message.first + " " + to_string(message.second) + "\r\n";
strcpy(buffer, str.c_str());
/* Send message to the server */
n = write(sockfd, buffer, strlen(buffer));
if (n < 0) {
throw "write to socket failed";
}
//cout << "sent: " << str << endl;
/* todo Now read server response - is needed?*/
//bzero(buffer, 256);
//n = read(sockfd, buffer, 255);
//if (n < 0) {
// throw "reading from socket failed";
//}
//printf("%s\n", buffer);
}
}
} catch (char const *exception) {
printf("%s",exception);
}
}
DataSetClient::~DataSetClient() {
close(this->sockfd);
}