-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathClientSocket.h
97 lines (79 loc) · 2.05 KB
/
ClientSocket.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
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
#ifndef _ClientSocket_H_
#define _ClientSocket_H_
#include "Tools.h"
class ClientSocket
{
public:
ClientSocket(std::string const &, int );
virtual ~ClientSocket();
inline void putc(char c)
{
if (n == BUFFER_SIZE)
flushBuffer();
buffer[n++] = c;
}
inline void putulong(ulong u)
{
if (u < (1u << 7))
{
uchar c = (u & 0xFFlu) | (1lu << 7);
putc(c);
return;
}
char l = 0;
ulong tmp = u;
do {
++l;
} while ((u >>= 8));
putc(l);
u = tmp;
do {
putc(u & 0xFFlu);
} while ((u >>= 8));
}
inline void putstring(std::string const &str)
{
for (size_t i = 0; i < str.size(); ++i)
putc(str[i]);
putc('.');
}
ulong checkHalt(unsigned &depth)
{
ulong u[2];
u[0] = 0;
u[1] = 0;
ssize_t nread = readnonblocking(sockfd, (char *)&u, sizeof(ulong)*2);
if (nread <= 0)
return 0;
if (nread != sizeof(ulong)*2)
{
std::cerr << "ClientSocket::checkHalt(): nonblocking read failed!" << std::endl;
std::exit(1);
}
if ((u[0] & 0xFF) != (ulong)'H')
{
std::cerr << "ClientSocket::checkHalt(): malformed halt!" << std::endl;
std::exit(1);
}
depth = (unsigned) (u[0]>>8);
if (depth == 0)
{
std::cerr << "ClientSocket::checkHalt(): depth == 0?!" << std::endl;
std::exit(1);
}
return u[1];
}
protected:
void flushBuffer();
static const unsigned BUFFER_SIZE = 16*1024; ///1024*1024;
ssize_t readnonblocking(int fd, char *vptr, size_t n);
char buffer[BUFFER_SIZE];
unsigned n; // number of bytes in buffer
int sockfd;
private:
ClientSocket();
// No copy constructor and assignment
ClientSocket(ClientSocket const&);
ClientSocket& operator = (ClientSocket const&);
};
#endif // _ClientSocket_H_