-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamReader.cpp
More file actions
69 lines (51 loc) · 1.54 KB
/
Copy pathstreamReader.cpp
File metadata and controls
69 lines (51 loc) · 1.54 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
#include "streamReader.h"
#include <cassert>
#include <poll.h>
#include <unistd.h>
#include "vpException.h"
#include "log.h"
//#define DEBUGE_INPUT
StreamReader::StreamReader(int socket, std::chrono::milliseconds timeout,
std::size_t bufferSize)
: m_socket(socket),
m_timeLeft(timeout),
m_bufSize(bufferSize),
m_buffer(new char[bufferSize])
{
assert(socket > -1);
assert(bufferSize > 0);
}
CharRange StreamReader::read()
{
if (m_timeLeft.count() == 0)
throw ReaderTimeout();
if (m_bufPos == m_bufSize)
throw ReaderBufferOverflow();
pollfd pollInfo = {};
pollInfo.fd = m_socket;
pollInfo.events = POLLIN;
using namespace std::chrono;
auto startTime = steady_clock::now();
int pollStatus = poll(&pollInfo, 1, m_timeLeft.count());
auto now = steady_clock::now();
auto dur = duration_cast<milliseconds>(now - startTime);
if (dur > m_timeLeft)
m_timeLeft = milliseconds(0);
else
m_timeLeft -= dur;
if (pollStatus == 0)
throw ReaderTimeout();
else if (pollStatus == -1)
throw ReaderError(errno);
int count = ::read(m_socket, m_buffer.get() + m_bufPos, m_bufSize - m_bufPos);
if (count == 0)
return CharRange();
else if (count == -1)
throw ReaderError("Read error", errno);
CharRange result(m_buffer.get() + m_bufPos, m_buffer.get() + m_bufPos + count);
#ifdef DEBUGE_INPUT
PRINT_LOG("receive: " << result.toString());
#endif
m_bufPos += count;
return result;
}