-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_sock.h
More file actions
79 lines (62 loc) · 1.63 KB
/
client_sock.h
File metadata and controls
79 lines (62 loc) · 1.63 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
#ifndef CLIENTSOCK_H
#define CLIENTSOCK_H
#include <iostream>
#include <future>
#include <functional>
#include <sstream>
#include <errno.h>
#include <string>
//#include <WinSock2.h>
#include <sys/types.h>
#include <sys/stat.h>
using namespace std;
class ClientSock {
public:
ClientSock(string host, unsigned int port);
ClientSock();
ClientSock(int sock);
~ClientSock();
int connect(string host, unsigned int port);
int reconnect();
int disconnect();
int write(const string & mesg);
string read();
string host;
unsigned int port;
bool connected;
private:
int socket;
struct sockaddr_in servaddr;
struct hostent* server;
};
class Client {
ClientSock socket;
public:
std::stringstream stream;
Client() = delete;
Client(const std::string & host, unsigned int port) { socket.connect(host, port); }
~Client() { socket.disconnect(); };
int write(const std::string & buffer) {
std::cout << "write : " << buffer << std::endl;
std::cout.flush();
return socket.write(buffer + "\n");
}
std::string readToken() {
std::string s;
stream >> s;
if (s == "")
return read();
std::cout << "try to read : \'" << s << "\'" << std::endl;
return s;
}
std::string read() {
if (stream.str() == "" || stream.eof()) {
std::string new_buffer = socket.read();
std::cout << "read : \'" << new_buffer << "\'" << std::endl;
std::cout.flush();
stream = stringstream(new_buffer);
}
return readToken();
}
};
#endif // CLIENTSOCK_H