-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMatrixSearchClient.cpp
111 lines (94 loc) · 2.9 KB
/
MatrixSearchClient.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
//
// Created by t on 1/15/19.
//
#include "MatrixSearchClient.h"
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <iostream>
#include <cstring>
#include <string>
void *threadFunc(void *data) {
try {
cout << "client thread started" << endl;
Data *data1;
data1 = (Data *) data;
//int portno;
ssize_t n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
/* Create a socket point */
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
throw "socket creation failed";
}
server = gethostbyname(data1->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)data1->port);
/* Now connect to the server */
while (connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
sleep(1);
}
//send the message
for(auto it : *data1->message) {
memset(buffer, 0, 256);
strcpy(buffer, it.c_str());
/* Send message to the server */
n = write(sockfd, buffer, strlen(buffer));
if (n < 0) {
throw "write to socket failed";
}
cout << "sent: " << it << endl;
sleep(1);
}
//read server response
memset(buffer, 0, 256);
n = read(sockfd, buffer, 255);
if (n < 0) {
throw "reading from socket failed";
}
printf("%s\n", buffer);
close(sockfd);
} catch (char const *exception) {
printf("%s",exception);
}
}
void MatrixSearchClient::open(string ipAddress, int port, vector<string> *message) {
cout << "client open" << endl;
//create a thread to talk with each client, one after the other
//pthread_t threadID;
this->data = new Data;
data->port = port;
data->message = message;
data->ipAddress = ipAddress;
//start the thread
//int rc = pthread_create(&threadID, NULL, serverThreadFunc, (void *)serverData);
int rc = pthread_create(&this->threadID, nullptr, threadFunc, (void *)data);
if (rc) {
throw "unable to create thread";
}
}
void MatrixSearchClient::stop() {
//close the thread
void *res;
int s = pthread_join(threadID, &res);
cout << "back from join client" << endl;
if (s != 0) {
throw "error in join thread";
}
//free memory allocated by thread
//free(res);
cout << "after free memory thread" << endl;
delete this->data;
this->data = nullptr;
cout << "end of client" << endl;
}